像使用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);
    }
posted @ 2022-06-17 20:51  Oh,mydream!  阅读(12)  评论(0编辑  收藏  举报