Java Reference
In-Depth Information
Utilize the Collections.sort() method, passing the list to sort along with a
lambda expression that performs the comparisons on the list elements. The following
code demonstrates how to accomplish this task using the Collections.sort()
technique.
Collections.sort(team, (p1, p2)
-> p1.getLastName().compareTo(p2.getLastName()));
team.stream().forEach((p) -> {
System.out.println(p.getLastName());
});
Result:
== Sort by Last Name ==
Adams
Gennick
Java
Juneau
Smith
Note This solution could be further simplified if the Player class included a com-
parison method. If this were the case, a method reference could be used, rather than im-
plementing a lambda expression. For more information regarding method references,
see Recipe 6-9.
How It Works
Java 8 introduces some new features that greatly increase developer productivity for
sorting collections. Three new features are demonstrated in the solution to this recipe:
lambda expressions, method references, and streams. We will look into streams and
method references in more detail within other recipes in this topic, but we also briefly
describe them here to enable the understanding of this recipe. Streams can be applied to
collections of data, and they allow enhanced functional-style operations to be applied
to the elements within the collections. Streams do not store any data; rather, they en-
able more functionality on the collections from which they are obtained.
Search WWH ::




Custom Search