2016-07-22 143 views
5

假設我有一個領域模型是這樣的:Comparator.comparing(...)嵌套場

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

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

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

現在,我可以創造一個老師比較喜歡這樣的:

return Comparator 
      .comparing(Teacher::getAge); 

但如何我會比較一下嵌套字段的講座嗎?

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

我不能在模型上添加一個方法Lecture.getTeacherAge()

+2

爲什麼不使用lambda? – njzk2

+0

啊......那一刻,當我意識到我問了一個愚蠢的問題:)(不是說有什麼愚蠢的問題。) –

回答

12

您不能嵌套方法引用。您可以使用lambda表達式來代替:

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

不幸的是,在java中的沒有很好的語法。

如果你想重用比較的部分,我可以看到2種方式:

  • 通過組合比較

    return comparing(Lecture::getCourse, comparing(Course::getTeacher, comparing(Teacher::getAge))) 
         .thenComparing(Lecture::getCourse, comparing(Course::getStudentSize)); 
    
    // or with separate comparators 
    Comparator<Teacher> byAge = comparing(Teacher::getAge); 
    Comparator<Course> byTeacherAge = comparing(Course::getTeacher, byAge); 
    Comparator<Course> byStudentsSize = comparing(Course::getStudentSize); 
    return comparing(Lecture::getCourse, byTeacherAge).thenComparing(Lecture::getCourse, byStudentsSize); 
    
  • 通過組合吸氣功能

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