问题
Could any one suggest idea to sort the list accordingly : suppose the List contains :
-SP001 of 2017
-SP002 of 2015
-SP001 of 2015
-SP001 of 2016
-SP005 of 2015
-SP003 of 2015
The the out put should be (List must contain in the below order) :
-SP001 of 2015
-SP002 of 2015
-SP003 of 2015
-SP005 of 2015
-SP001 of 2016
-SP001 of 2017
here i need to sort according to number part as well as year part. I have tried collection sort but it gives out put like :
[SP001 of 2015, SP001 of 2016, SP001 of 2017, SP002 of 2015, SP003 of 2015, SP005 of 2015]
回答1:
You can try this: First split the strings and then compare the third element of array.
List<String> list = new ArrayList<>();
list.add("-SP005 of 2015");
list.add("-SP001 of 2017");
list.add("-SP003 of 2015");
list.add("-SP001 of 2015");
list.add("-SP001 of 2016");
list.add("-SP002 of 2015");
Collections.sort(list, new Comparator<String>() {
public int compare(String o1, String o2) {
int result = o1.split(" ")[2].compareTo(o2.split(" ")[2]);
if (result == 0) {// if the years are the same, then compare with first element
return o1.split(" ")[0].compareTo(o2.split(" ")[0]);
}
return result;
}
});
System.out.println("list = " + list);
And it is the result:
list = [
-SP001 of 2015,
-SP002 of 2015,
-SP003 of 2015,
-SP005 of 2015,
-SP001 of 2016,
-SP001 of 2017
]
回答2:
For java-8
You may use two Comparator<String> and the method thenComparing within the Collections#sort method
The first comparator will compare the years, while the second will compare the second String and so directly the first part of each one.
Comparator<String> comp1 = (x, y) -> x.split(" ")[2].compareTo(y.split(" ")[2]);
Comparator<String> comp2 = (x, y) -> x.compareTo(y);
Collections.sort(list, comp1.thenComparing(comp2));
System.out.println(list);
Output
[SP001 of 2015, SP002 of 2015, SP003 of 2015, SP005 of 2015, SP001 of 2016, SP001 of 2017]
来源:https://stackoverflow.com/questions/36028450/sort-a-collection-list-with-two-numeric-parts-of-string-in-java