Java教程

像使用sql一样排序集合

本文主要是介绍像使用sql一样排序集合,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

像使用sql一样排序集合

使用集合自己的排序功能,并写自己的Comparator接口

实践

 @Test
    public void Test6() {
        Employee e1 = new Employee(1, 21, "zhangsan", "F");
        Employee e2 = new Employee(2, 45, "lisi", "M");
        Employee e3 = new Employee(3, 60, "wangwu", "M");
        Employee e4 = new Employee(4, 32, "zhouliu", "F");
        Employee e5 = new Employee(5, 28, "zhaoqi", "M");
        Employee e6 = new Employee(6, 43, "qianba", "F");

        List<Employee> list = Arrays.asList(e1, e2, e3, e4, e5, e6);

        // 都是正序
        list.sort(Comparator.comparing(Employee::getGender).thenComparingInt(Employee::getAge));
        list.forEach(System.out::println);
        // 都是逆序
        list.sort(Comparator.comparing(Employee::getGender).thenComparingInt(Employee::getAge).reversed());
        list.forEach(System.out::println);
        // 一逆一正
        list.sort(Comparator.comparing(Employee::getGender).reversed().thenComparingInt(Employee::getAge));
        list.forEach(System.out::println);
        // 一正一逆
        list.sort(Comparator.comparing(Employee::getGender).reversed().thenComparingInt(Employee::getAge).reversed());
        list.forEach(System.out::println);
    }
这篇关于像使用sql一样排序集合的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!