用Java中的字符串的两个数字部分对Collection列表进行排序 [英] Sort a Collection list with two numeric parts of string in Java

查看:81
本文介绍了用Java中的字符串的两个数字部分对Collection列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以提出想法对列表进行相应的排序: 假设列表包含:

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]

推荐答案

您可以尝试以下操作:首先拆分字符串,然后比较数组的第三个元素.

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);

它是结果:

list = [
-SP001 of 2015, 
-SP002 of 2015, 
-SP003 of 2015, 
-SP005 of 2015, 
-SP001 of 2016, 
-SP001 of 2017
]

这篇关于用Java中的字符串的两个数字部分对Collection列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆