Java中如何实现List的自定义排序

最近项目中遇到一个问题,需要对List进行自定义顺序排序,打个比方,现在我有一个SortStudent类,需要对它的年龄降序排序,再对他的省份进行自定义的排序,要求按照:"安徽", "北京", "上海", "深圳", "广州"的顺序排列,如何实现呢?直接上代码,很简单,关键地方有注释,应该是一目了然的。

public class CustomSort {
    private static final List<String> regulationOrder = Arrays.asList("安徽", "北京", "上海", "深圳", "广州");

    public static void main(String[] args) {
        List<SortStudent> students = new ArrayList<>();
        SortStudent student1 = new SortStudent("Mike", 5, "上海");
        SortStudent student2 = new SortStudent("Mike", 5, "安徽");
        SortStudent student3 = new SortStudent("Mike", 5, "北京");
        SortStudent student4 = new SortStudent("Mike", 4, "深圳");
        SortStudent student5 = new SortStudent("Mike", 4, "安徽");
        SortStudent student6 = new SortStudent("Mike", 6, "南京");
        SortStudent student7 = new SortStudent("Mike", 6, "广州");

        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);
        students.add(student5);
        students.add(student6);
        students.add(student7);

        //根据省份排序
        students.sort((o1, o2) -> {
            int index1 = regulationOrder.indexOf(o1.getProvince());
            if (index1 == -1)
                return 1;
            int index2 = regulationOrder.indexOf(o2.getProvince());
            if (index2 == -1)
                return -1;
            return index1 - index2;
        });

        //注意:低优先级的要先排序,这样高优先级的才不会被打乱,我这里高优先级的是age,低优先级的是province
        //根据年龄降序排序,stream排序不改变原始list顺序
        //结果:先按年龄降序,再按省份特定顺序排序
        List<SortStudent> sortedList = students.stream()
                .sorted(Comparator.comparing(SortStudent::getAge).reversed()).collect(Collectors.toList());

        for (int i = 0; i < students.size(); i++) {
            System.out.println("省份排序后: " + students.get(i).getProvince() + " - " + students.get(i).getAge()
                    + "    年龄排序后: " + sortedList.get(i).getProvince() + " - " + sortedList.get(i).getAge());
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class SortStudent {
        private String name;
        private int age;
        private String province;
    }
}

执行效果如下: 

可以看到,结果达到了我们想要的效果。 

©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页