Java 8 比较器链接,在单个属性上反向

2022-09-01 18:51:54

我正在使用 a 对对象列表进行排序。ComparatorStudent

我想反转对属性的排序,但使用方法将其应用于整个排序。idreverse()

如何使它只发生在?id

这是我到目前为止的代码:

 public List<Student> getStudents(List<String> events) {
    Comparator<Student> comparatorStudents = Comparator.comparing(Student::getCGPA).thenComparing(Student::getName)
      .thenComparingInt(Student::getID).reverse();
    List<Student> students = new ArrayList<Student>();
    //Filling students
    Collections.sort(students, comparatorStudents);
    return students;
  }

答案 1

将最后一位更改为:

.thenComparing(Student::getID, Comparator.reverseOrder())

或者,如果您想避免自动装箱:

.thenComparing(Comparator.comparingInt(Student::getID).reversed())

答案 2

reversed() 的调用放入:thenComparing

public List<Student> getStudents(List<String> events) {
    Comparator<Student> comparatorStudents = Comparator.comparing(Student::getCGPA)
       .thenComparing(Student::getName)
       .thenComparing(Comparator.comparingInt(Student::getID).reversed());
    List<Student> students = new ArrayList<Student>();
    //Filling students
    Collections.sort(students, comparatorStudents);
    return students;
}

推荐