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

查看:98
本文介绍了嵌套字段的 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());

注意:在某些情况下,您需要明确说明泛型类型.例如,如果在 Java 8 中 comparing(...) 之前没有 ,下面的代码将无法工作.

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天全站免登陆