Java Reference
In-Depth Information
Map
<
Artist
,
Integer
>
countOfAlbums
=
new
new
HashMap
<>();
albumsByArtist
.
forEach
((
artist
,
albums
) -> {
countOfAlbums
.
put
(
artist
,
albums
.
size
());
});
Key Points
▪ Method references are a lightweight syntax for referring to methods and look like this:
ClassName::methodName
.
▪ Collectors let us compute the final values of streams and are the mutable analogue of the
reduce
method.
▪ Java 8 provides out-of-the-box support for collecting into many collection types and the
ability to build custom collectors.
Exercises
1.
Method references.
Take a look back at the examples in
Chapter 3
and try rewriting
the following using method references:
a. The
map
to uppercase
b. The implementation of
count
using
reduce
c. The
flatMap
approach to concatenating lists
2.
Collectors.
a. Find the artist with the longest name. You should implement this using a
Col-
the differences in your implementation: which was easier to write and which
was easier to read? The following example should return
"Stuart
Sutcliffe"
:
Stream
<
String
>
names
=
Stream
.
of
(
"John Lennon"
,
"Paul McCartney"
,
"George Harrison"
,
"Ringo Starr"
,
"Pete Best"
,
"Stuart Sutcliffe"
);