2016-07-22 11 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

क्यों द्वारा रचना तुलनाकारक

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); 
  • द्वारा एक लैम्ब्डा का उपयोग नहीं करते? – njzk2

  • +0

    आह ... उस पल जब मुझे एहसास हुआ कि मैंने एक बेवकूफ सवाल पूछा है :) (नहीं कि कोई बेवकूफ सवाल हैं।) –

    उत्तर

    12

    आप विधि संदर्भों को घोंसला नहीं दे सकते हैं। आप इसके बजाय लैम्ब्डा अभिव्यक्तियों का उपयोग कर सकते हैं:

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

    दुर्भाग्यवश इसके लिए जावा में कोई अच्छा वाक्यविन्यास नहीं है।

    मैं 2 तरीके से देख सकते हैं आप तुलनित्र के कुछ हिस्सों का पुन: उपयोग करना चाहते हैं:

    • रचना गेटर कार्यों

      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); 
      
    संबंधित मुद्दे