问题
I have an ArrayList made up of strings. This ArrayList contains...
"60 Minutes" "120 Minutes" "30 Minutes"
If I use Collections.sort(ArrayList);
it results in "120 Minutes" first. This is because the "1" in "120 is obviously smaller than the "3" in "30"
Is there a simple way I can sort this ArrayList so that it shows up as...
"30 Minutes" "60 Minutes" "120 Minutes"
回答1:
Define your own class that implements Comparator<String>. In the compare
method, extract the numbers out of the first part of the string arguments and compare them, returning -1, 0, or 1, if the first number is less than, equal to, or greater than, the second number.
Then you can pass an instance of your comparator (along with your ArrayList
) to Collections.sort.
回答2:
With Java 8 you could make it a one line operation with something like:
Collections.sort(list, comparing(s -> Integer.valueOf(s.split("\\s+")[0])));
However that still requires some messy logic to perform the comparison.
It would probably be cleaner and easier to maintain to create an ad-hoc class that holds the information in the form of an int
and implements the Comparable
interface.
回答3:
Using @rgettman's idea, and assuming all strings are properly formatted as in your example input, the comparison itself could be something like this:
int spcIdx = s1.indexOf(" ");
int i1 = s1.substring(0, spcIdx);
String s1 = s1.substring(spcIdx + 1);
//Repeat for i1 and s2...
return (((new Integer(i1)).compareTo(i2) * 10) + s1.compareTo(s2));
来源:https://stackoverflow.com/questions/22669270/sorting-an-arraylist-that-contains-strings-with-numbers