List集合单属性有序过滤

学生对象

@Data
public class Student {
          
   
    private String name;
    private Integer age;
    private Integer group;

    public Student(String name, Integer age, Integer group) {
          
   
        this.name = name;
        this.age = age;
        this.group = group;
    }
    public Student() {
          
   
        super();
    }
}

Stream操作

public static void main(String[] args) {
          
   

        List<Student> studentList = Arrays.asList(
                new Student("多多", 20, 1),
                new Student("多多", 7, 1),
                new Student("鹏鹏", 1, 8),
                new Student("鹏鹏", 2, 8),
                new Student("鹏鹏", 3, 8),
                new Student("鹏鹏", 4, 8),
                new Student("鹏鹏", 5, 8),
                new Student("鹏鹏", 6, 8),
                new Student("鹏鹏", 7, 8),
                new Student("鹏鹏", 8, 8),
                new Student("青青", 4, 9),
                new Student("青青", 4, 9),
                new Student("香蕉", 45, 3),
                new Student("香蕉", 45, 3),
                new Student("柠檬", 2, 2),
                new Student("柠檬", 12, 2),
                new Student("柠檬", 87, 2),
                new Student("绿绿", 45, 3),
                new Student("绿绿", 45, 3),
                new Student("小红", 3, 2),
                new Student("小红", 1, 2),
                new Student("小白", 4, 6),
                new Student("小白", 2, 6),
                new Student("苹果", 1, 3),
                new Student("苹果", 2, 3),
                new Student("小黑", 5, 1));
		// 使用TreeSet进行比较得到的过滤key会是有序的
        ArrayList<Student> collect = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(Student::getGroup))), ArrayList::new));


        collect.forEach(System.out::println);

    }
经验分享 程序员 微信小程序 职场和发展