Java Reference
In-Depth Information
Solution 1
Create a Comparator using an accessor method contained within the Player object
for the field by which you want to sort. In this case, you want to sort by number of
goals, so the Comparator should be based upon the value returned from
getGoals() . The following line of code shows how to create such a Comparator
using the Comparator interface and a method reference.
Comparator<Player> byGoals
= Comparator.comparing(Player::getGoals);
Next, utilize a mixture of lambda expressions and streams (See Chapter 7 for full
details on streams), along with the forEach() method, to apply the specified sort on
the list of Player objects. In the following line of code, a stream is obtained from the
list, which allows you to apply functional-style operations on the elements.
team.stream().sorted(byGoals)
.map(p -> p.getFirstName() + " "
+ p.getLastName() + " - "
+ p.getGoals())
.forEach(element ->
System.out.println(element));
Assuming that the List referenced by team is loaded with Player objects, the
previous line of code will first sort that list by the Player goals, and then print out in-
formation on each object.
Results from the sort:
== Sort by Number of Goals ==
Jonathan Gennick - 1
Josh Juneau - 5
Steve Adams - 7
Duke Java - 15
Bob Smith - 18
Solution 2
Search WWH ::




Custom Search