List按照实体的多个字段进行排序
实体类
@Data
public class Student {
private Long id;
private String name;
private Double score;
public Student() {}
public Student(Long id, String name, Double score) {
this.id = id;
this.name = name;
this.score = score;
}
}
测试类
public class TestSort {
public static void main(String[] args) {
List<Student> studentList = Arrays.asList(
new Student(1L, "张三", 95.5d),
new Student(2L, "李四", 97.5d),
new Student(3L, "王五", 95.5d),
new Student(4L, "赵六", 96.5d),
new Student(5L, "钱七", 98.5d),
new Student(6L, "小二", 97d)
);
Comparator<Student> byScore = Comparator.comparing(Student::getScore, (s1, s2) -> {
return s2.compareTo(s1);
});//按照分数降序
Comparator<Student> byName = Comparator.comparing(Student::getName);//按照名字字典升序
Collections.sort(studentList,byScore.thenComparing(byName));//先按照分数降序,再按照名字升序
System.out.println(studentList);
}
}