简体   繁体   中英

Sort a ArrayList<String> by number value

I have an ArrayList of video resolutions that looks like this:

"1024x768", "800x600", "1280x1024", etc

I want to sort it based on numeric value in first part of string. Ie, the above would sort out to look like this:

"800x600","1024x768","1280x1024"

Is there a quick and dirty way to do this, by that I mean in less then 2-3 lines of code? If not, what would be the proper way? The values I get are from an object not my own. It does have a getWidth() and getHeight() methods that return ints.

If the objects in the array are Resolution instances with getWidth methods then you can use a Comparator to sort on those:

Collections.sort(resolutions, new Comparator {
    public int compare(Resolution r1, Resolution r2) {
        return Integer.valueOf(r1.getWidth()).compareTo(Integer.valueOf(r2.getWidth()));
    }
});

The proper way is to write a Comparator implementation that operates on Strings, except that it parses up to the first non-numeric character. It then creates an int out of that and compares the ints.

You can then pass an instance of that Comparator into Collections.sort() along with your List.

使用自定义Comparator通过Collections api对ArrayList进行排序。

Collections.sort(resolutionArrayList, new ResolutionComparator())

Using a Comparator will work, but will get slow if you have lots of values because it will parse each String more than once.

An alternative is to add each value to a TreeMap, with the number you want as the key, ie, Integer.valueOf(s.substring(0,s.indexOf('x'))) , then create a new ArrayList from the sorted values in treeMap.values() .

The solution suggested by Shadwell in his answer is correct and idiomatic.

But if you're looking for a more concise solution, then I'd advise you use lambdaj which will enable you to write code like:

List<Resolution> sortedResolutions = sort(resolutions, on(Resolution.class).getWidth());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM