Sort ArrayList <String> by number

I have an ArrayList video solution that looks like this:

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

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

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

Is there a quick and dirty way to do this, I mean less than 2-3 lines of code? If not, what will be the right way? The values ​​that I receive refer to an object that does not belong to me. It has getWidth () and getHeight () methods that return ints.

+3
source share
5 answers

Resolution getWidth , Comparator :

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

- , Strings, , . int ints.

Collections.sort() .

0

ArrayList api.

Collections.sort(resolutionArrayList, new ResolutionComparator())
0

, , , .

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

0
source

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

But if you are looking for a more concise solution, I would advise you to use lambdaj , which will allow you to write code like:

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

Source: https://habr.com/ru/post/1764993/


All Articles