I have a string list as follows:
(2D, 1D, 1Y, 23M, 4M, 2Y, 12D)
How can I sort it alphabetically and then numerically?
I expect
(1D, 2D, 12D, 4M, 23M, 1Y, 2Y)
I tried this but it didn't work.
Collections.sort(myList, new MyComparator());
public class MyComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
String strPart1 = s1.split("")[1];
int intPart1 = Integer.parseInt(s1.split("")[0]);
String strPart2 = s2.split("")[1];
int intPart2 = Integer.parseInt(s2.split("")[0]);
int strCompareResult = strPart1.compareTo(strPart2);
if(0 == strCompareResult )
{
return intPart1 - intPart2;
}
else
{
return strCompareResult;
}
}
}
However this did not work.
You can sort first by the last character, then parse the other characters as an int
. The Comparator
can be written more easily with the Comparator.comparing
and .thenComparing
methods.
myList.sort(Comparator.comparing((String s) -> s.charAt(s.length() - 1))
.thenComparingInt(s -> Integer.parseInt(s.substring(0, s.length() - 1))));