Sort a Collection list with two numeric parts of string in Java

感情迁移 提交于 2019-12-25 18:28:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!