2016-07-22 27 views
5

Giả sử tôi có một mô hình miền như thế này:Comparator.comparing (...) của một trường lồng nhau

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

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

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

Bây giờ tôi có thể tạo ra một sánh giáo viên như thế này:

return Comparator 
      .comparing(Teacher::getAge); 

Nhưng làm thế nào sao tôi so sánh Bài giảng trên các lĩnh vực lồng nhau, như thế này?

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

Tôi không thể thêm phương thức Lecture.getTeacherAge() vào kiểu máy.

+2

tại sao không sử dụng lambda? – njzk2

+0

Ah ... khoảnh khắc đó khi tôi nhận ra rằng tôi đã hỏi một câu hỏi ngu ngốc :) (Không phải là có bất kỳ câu hỏi ngu ngốc nào.) –

Trả lời

12

Bạn không thể lồng tham chiếu phương thức. Thay vào đó, bạn có thể sử dụng biểu thức lambda:

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

Thật không may là không có cú pháp nào trong java cho điều đó.

Nếu bạn muốn sử dụng lại các bộ phận của so sánh tôi có thể thấy 2 cách:

  • bằng cách soạn bộ so sánh

    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); 
    
  • bằng cách soạn chức năng getter

    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); 
    
Các vấn đề liên quan