Comparator.comparing(…) of a nested field

前端 未结 3 976
轻奢々
轻奢々 2020-11-30 09:53

Suppose I have a domain model like this:

class Lecture {
     Course course;
     ... // getters
}

class Course {
     Teacher teacher;
     int studentSize         


        
3条回答
  •  长情又很酷
    2020-11-30 10:31

    Unfortunately there is no nice syntax in java for that.

    If you want to reuse parts of comparator I can see 2 ways:

    • by composing comparators

      return comparing(Lecture::getCourse, comparing(Course::getTeacher, comparing(Teacher::getAge)))
             .thenComparing(Lecture::getCourse, comparing(Course::getStudentSize));
      
      // or with separate comparators
      Comparator byAge = comparing(Teacher::getAge);
      Comparator byTeacherAge = comparing(Course::getTeacher, byAge);
      Comparator byStudentsSize = comparing(Course::getStudentSize);
      return comparing(Lecture::getCourse, byTeacherAge).thenComparing(Lecture::getCourse, byStudentsSize);
      
    • by composing getter functions

      Function getCourse = Lecture::getCourse;            
      return comparing(getCourse.andThen(Course::getTeacher).andThen(Teacher::getAge))
             .thenComparing(getCourse.andThen(Course::getStudentSize));
      
      // or with separate getters
      Function getCourse = Lecture::getCourse;
      Function teacherAge = getCourse.andThen(Course::getTeacher).andThen(Teacher::getAge);
      Function studentSize = getCourse.andThen(Course::getStudentSize);
      return comparing(teacherAge).thenComparing(studentSize);
      

提交回复
热议问题