如何从方法参考创建比较器?

时间:2018-11-20 18:23:22

标签: java lambda

我正在学习lambda表达式。我不明白如何从方法引用中返回比较器。

我想按年龄对人员列表进行排序。

为此,我有一种方法来查找年龄差异:

public int ageDifference(final Person other) { return age - other.age; } 方法需要将sorted作为参数

Comparator

我的lambda表达式是:

Stream<T> sorted(Comparator<? super T> comparator);

如何在people.stream() .sorted(Person::ageDifference) .collect(toList()); 中转换Person::ageDifference

我的完整示例:

Comparator<Person>

输出:public class Person { private final String name; private final int age; public Person(final String theName, final int theAge) { name = theName; age = theAge; } public String getName() { return name; } public int getAge() { return age; } public int ageDifference(final Person other) { return age - other.age; } public String toString() { return String.format("%s - %d", name, age); } public static void main (String args[] ){ final List<Person> people = Arrays.asList( new Person("John", 10), new Person("Greg", 30), new Person("Sara", 20), new Person("Jane", 15)); List<Person> ascendingAge = people.stream() .sorted(Person::ageDifference) .collect(toList()); System.out.println(ascendingAge); } }

1 个答案:

答案 0 :(得分:5)

我想你的主要困惑是:

  

Comparator<T>表示一种方法,该方法采用两个T类型的参数并返回一个int。我的ageDifference方法仅接受一个Person参数。那怎么能变成Comparator<Person>

请注意,ageDifference是一个实例方法。要调用它,不仅需要参数,还需要Person的实例。在这种情况下,您需要2个Person来调用该方法-一个在上面调用ageDifference,另一个在您作为参数传递时:

me.ageDifference(someoneElse)
^                      ^
|                      |
        Two people!

这不是就像接受两个参数的static方法吗?

因此,Java足够聪明,知道您需要两个人来调用Person::ageDifference,因此方法引用被视为具有两个参数。

通常,类T的实例方法接受参数P1P2 ... Pn并返回类型R可以视为接受参数TP1P2 ... Pn并返回R的静态方法。