Geoffrey De Smet Geoffrey De Smet - 4 months ago 12
Java Question

Comparator.comparing(...) of a nested field

Suppose I have a domain model like this:

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

class Course {
Teacher teacher;
int studentSize;
... // getters
}

class Teacher {
int age;
... // getters
}


Now I can create a Teacher Comparator like this:

return Comparator
.comparing(Teacher::getAge);


But how do I compare Lecture's on nested fields, like this?

return Comparator
.comparing(Lecture::getCourse::getTeacher:getAge)
.thenComparing(Lecture::getCourse::getStudentSize);


I can't add a method
Lecture.getTeacherAge()
on the model.

Answer

You can't nest method references. You can use lambda expressions instead :

return Comparator
        .comparing(l->l.getCourse().getTeacher().getAge(), Comparator.reverseOrder()) 
        .thenComparing(l->l.getCourse().getStudentSize());