我正在学习lambda表达式.我不明白如何从方法引用返回比较器.
我想按年龄排序一份人员名单.
要做到这一点,我有一个方法来找到年龄差异:
public int ageDifference(final Person other) {
return age - other.age;
}
Run Code Online (Sandbox Code Playgroud)
该sorted方法需要作为参数aComparator
Stream<T> sorted(Comparator<? super T> comparator);
Run Code Online (Sandbox Code Playgroud)
我的lambda表达式是:
people.stream()
.sorted(Person::ageDifference)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
怎么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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出: [John - 10, Jane - 15, Sara - 20, Greg - 30]
我想你的主要困惑是:
Comparator<T>表示一个方法,它接受两个类型的参数T并返回一个int.我的ageDifference方法只接受一个Person参数.怎么会成为一个Comparator<Person>?
请注意,这ageDifference是一个实例方法.要调用它,不仅需要参数,还需要一个实例Person.在这种情况下,你需要2 Person秒来调用方法 - 一个你调用的方法ageDifference,另一个你作为参数传递:
me.ageDifference(someoneElse)
^ ^
| |
Two people!
Run Code Online (Sandbox Code Playgroud)
这不就像一个static接受两个参数的方法吗?
因此,Java足够聪明,知道您需要两个人来调用Person::ageDifference,因此方法引用被视为具有两个参数.
在一般情况下,一个类的实例方法T接受参数P1,P2... Pn和返回类型R可以被视为一个静态方法接受参数T,P1,P2... Pn和返回R.