Chapter 5. Advanced Collections and Collectors
Thereâs a lot more to the collections library changes than I covered in Chapter 3. Itâs time to cover some of the more advanced collections
changes, including the new Collector
abstraction. Iâll also introduce method
references, which are a way of using existing code in lambda expressions with
little to no ceremony. They pay huge dividends when it comes to writing
Collection
-heavy code. More advanced topics within the collections library
will also be covered, such as element ordering within streams and other useful API
changes.
Method References
A common idiom you may have noticed is the creation of a lambda expression that calls a method on its parameter. If we want a lambda expression that gets the name of an artist, we would write the following:
artist
->
artist
.
getName
()
This is such a common idiom that thereâs actually an abbreviated syntax for this that lets you reuse an existing method, called a method reference. If we were to write the previous lambda expression using a method reference, it would look like this:
Artist:
:
getName
The standard form is Classname::methodName
. Remember that even though itâs a
method, you donât need to use brackets because youâre not actually calling the
method. Youâre providing the equivalent of a lambda expression that can be
called in order to call the method. You can use method references in the same
places as lambda expressions.
You can also call constructors using the same abbreviated ...
Get Java 8 Lambdas now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.