Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

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

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...