On page 55, we see Compare.java
final Function<Person, String> byName = person -> person.getName();
people.stream()
.sorted(comparing(byName));
However, this can be further simplified to:
people.stream()
.sorted(comparing(Person::getName));
On the same page, more from Compare.java
:
final Function<Person, Integer> byAge = person -> person.getAge();
final Function<Person, String> byTheirName = person -> person.getName();
printPeople("Sorted in ascending order by age, then name: ",
people.stream()
.sorted(comparing(byAge).thenComparing(byTheirName))
.collect(toList());
which can be simplified similarly to:
printPeople("Sorted in ascending order by age, then name: ",
people.stream()
sorted(comparing(Person::getAge).thenComparing(Person::getName))
.collect(toList());
but which would be even better by separating the list generation and output tasks:
List<Person> asc =
people.stream()
.sorted(comparing(Person::getAge).thenComparing(Person::getName))
.collect(toList());
printPeople("Sorted in ascending order by age, then name: ", asc);
…all according to the JavaDoc for Comparator
:
P.S.
Would it be clearer to explicitly write the class from which comparing()
comes instead of assuming it has been imported statically? Like this:
people.stream()
.sorted(Comparator.comparing(Person::getName));
instaed of
people.stream()
.sorted(comparing(Person::getName));
Note that the collect()
call
people.stream()
.sorted(comparing(byAge).thenComparing(byTheirName))
.collect(toList()));
…also assume a statically imported toList()
. On the other hand, compare/fpij/OlderThan20.java
on page 58 is explicit:
List<Person> olderThan20 =
people.stream()
.filter(person -> person.getAge() > 20)
.collect(Collectors.toList());