假设我有一个这样的域模型:
class Lecture {
Course course;
... // getters
}
class Course {
Teacher teacher;
int studentSize;
... // getters
}
class Teacher {
int age;
... // getters
}
现在我可以像这样创建一个教师比较器:
return Comparator
.comparing(Teacher::getAge);
但是如何在嵌套字段上比较Lecture,像这样?
return Comparator
.comparing(Lecture::getCourse::getTeacher:getAge)
.thenComparing(Lecture::getCourse::getStudentSize);
我无法在模型上添加方法Lecture.getTeacherAge()
。
答案 0 :(得分:24)
您无法嵌套方法引用。您可以改为使用lambda表达式:
return Comparator
.comparing(l->l.getCourse().getTeacher().getAge(), Comparator.reverseOrder())
.thenComparing(l->l.getCourse().getStudentSize());
如果不需要逆向订单,它就会更加冗长:
return Comparator
.comparing(l->l.getCourse().getTeacher().getAge())
.thenComparing(l->l.getCourse().getStudentSize());
注意:在某些情况下,您需要明确说明泛型类型。例如,下面的代码在Java 8中没有<FlightAssignment, LocalDateTime>
comparing(...)
之前就无法工作。
flightAssignmentList.sort(Comparator
.<FlightAssignment, LocalDateTime>comparing(a -> a.getFlight().getDepartureUTCDateTime())
.thenComparing(a -> a.getFlight().getArrivalUTCDateTime())
.thenComparing(FlightAssignment::getId));
较新的java版本具有更好的自动类型检测功能,可能不需要。
答案 1 :(得分:10)
不幸的是,java中没有很好的语法。
如果你想重用部分比较器我可以看到两种方式:
通过编写比较器
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);
通过撰写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);
答案 2 :(得分:0)
npm config set msvs_version 2015 --global
npm install -g node-sass