Suppose I have a domain model like this:
class Lecture {
Course course;
... // getters
}
class Course {
Teacher teacher;
int studentSize
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);