Comparator.comparing(...)嵌套字段 [英] Comparator.comparing(...) of a nested field

查看:4338
本文介绍了Comparator.comparing(...)嵌套字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的域名模型:

Suppose I have a domain model like this:

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

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

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

现在我可以创建一名教师这样的比较器:

Now I can create a Teacher Comparator like this:

    return Comparator
            .comparing(Teacher::getAge);

但是如何在嵌套字段上比较Lecture,像这样?

But how do I compare Lecture's on nested fields, like this?

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

我无法添加方法 Lecture.getTeacherAge()在模型上。

I can't add a method Lecture.getTeacherAge() on the model.

推荐答案

您不能嵌套方法引用。您可以改为使用lambda表达式:

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

注意:在某些情况下,您需要明确说明泛型类型。例如,在比较(...)< FlightAssignment,LocalDateTime> ,下面的代码将无效>在Java 8中。

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

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

较新的java版本具有更好的自动类型检测功能,可能不需要。

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

这篇关于Comparator.comparing(...)嵌套字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆