Stream流排序相关

准备实体:

//使用lombok插件
@Data //相当于get/set方法
@AllArgsConstructor //有参构造器
@NoArgsConstructor  //无参构造器
@ToString
public class Teacher {
    private Long id;
    private String name;
    private Integer age;
}

案例1:使用Stream流对一个集合按照"年龄"升序排序

    //使用Stream流对一个集合按照"年龄"升序排序
    @Test
    public void streamDemo02(){
        List<Teacher> teacherList = new ArrayList<>();
        teacherList.add(new Teacher(1L, "张三", 20));
        teacherList.add(new Teacher(2L, "张三", 23));
        teacherList.add(new Teacher(3L, "李四", 21));
        teacherList.add(new Teacher(4L, "王五", 21));
        teacherList.add(new Teacher(5L, "赵六", 24));
        //按照年龄升序排序
        teacherList.stream().sorted(Comparator.comparing(Teacher::getAge)).forEach(System.out::println);
        /**结果:
         Teacher(id=1, name=张三, age=20)
         Teacher(id=3, name=李四, age=21)
         Teacher(id=4, name=王五, age=21)
         Teacher(id=2, name=张三, age=23)
         Teacher(id=5, name=赵六, age=24)
         */
    }

案例2:使用Stream流对一个集合"按照年龄"降序排序

    //使用Stream流对一个集合"按照年龄"降序排序
    @Test
    public void streamDemo03(){
        List<Teacher> teacherList = new ArrayList<>();
        teacherList.add(new Teacher(1L, "张三", 20));
        teacherList.add(new Teacher(2L, "张三", 23));
        teacherList.add(new Teacher(3L, "李四", 21));
        teacherList.add(new Teacher(4L, "王五", 21));
        teacherList.add(new Teacher(5L, "赵六", 24));
        //按照年龄升序排序
        teacherList.stream().sorted(Comparator.comparing(Teacher::getAge).reversed()).forEach(System.out::println);
        /**结果:
         Teacher(id=5, name=赵六, age=24)
         Teacher(id=2, name=张三, age=23)
         Teacher(id=3, name=李四, age=21)
         Teacher(id=4, name=王五, age=21)
         Teacher(id=1, name=张三, age=20)
         */
    }

案例3:使用Stream流对一个集合"按照年龄"降序排序 如果年龄相同按照id进行降序排序

//使用Stream流对一个集合"按照年龄"降序排序 如果年龄相同按照id进行降序排序
    @Test
    public void streamDemo04(){
        List<Teacher> teacherList = new ArrayList<>();
        teacherList.add(new Teacher(1L, "张三", 20));
        teacherList.add(new Teacher(2L, "张三", 23));
        teacherList.add(new Teacher(3L, "李四", 21));
        teacherList.add(new Teacher(4L, "王五", 21));
        teacherList.add(new Teacher(5L, "赵六", 24));
        //按照年龄升序排序
        teacherList.stream().sorted(Comparator.comparing(Teacher::getAge).reversed().thenComparing(Teacher::getId).reversed()).forEach(System.out::println);
        /**结果:
         Teacher(id=1, name=张三, age=20)
         Teacher(id=4, name=王五, age=21)
         Teacher(id=3, name=李四, age=21)
         Teacher(id=2, name=张三, age=23)
         Teacher(id=5, name=赵六, age=24)
         */
    }

上一篇:GO序列化


下一篇:关于delete视图的一个小实验