List集合排序之Java8stream流排序

1.新建测试JavaBean User.java

@Data
public class User {
     
    private int age;
    private String sex;
    private int grade;
}

2.:stream流根据年龄正序排序

resultList = resultList.stream().sorted(Comparator.comparing(User::getAge))
			.collect(Collectors.toList());

3:stream流根据年龄倒序排序

  • 在正序的基础上增加reversed
resultList = resultList.stream().sorted(Comparator.comparing(User::getAge)
			.reversed())
			.collect(Collectors.toList());

4:stream流先按学生年龄降序排序,年龄相等的话,则按年级升级排序

resultList =  resultList.stream().sorted(Comparator.comparing(User::getAge)
                              .reversed()
                              .thenComparing(Comparator.comparing(User::getGrade))
                    ).collect(Collectors.toList());

5:stream流先按年龄降序排序,再按年级降序排序

resultList =  resultList.stream().sorted(Comparator.comparing(User::getAge)
                              .reversed()
                              .thenComparing(Comparator.comparing(User::getGrade).reversed())
                    ).collect(Collectors.toList());

你可能感兴趣的:(Java,stream,java)