Comparator.comparing(…) of a nested field

前端 未结 3 979
轻奢々
轻奢々 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:12

    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());
    

    Without the need for reverse order it's even less verbose:

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

    Note: in some cases you need to explicitly state the generic types. For example, the code below won't work without the before comparing(...) in Java 8.

    flightAssignmentList.sort(Comparator
            .comparing(a -> a.getFlight().getDepartureUTCDateTime())
            .thenComparing(a -> a.getFlight().getArrivalUTCDateTime())
            .thenComparing(FlightAssignment::getId));
    

    Newer java version have better auto type detection and might not require that.

提交回复
热议问题