Я изучаю лямбда-выражения.Я не понимаю, как компаратор возвращается из ссылки на метод.
Я хочу отсортировать список людей по возрасту.
Для этого у меня есть метод, чтобы найти разницу в возрасте:
public int ageDifference(final Person other) {
return age - other.age;
}
Метод sorted
нуждается в качестве параметра a Comparator
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);
}
}
Вывод: [John - 10, Jane - 15, Sara - 20, Greg - 30]