Java Reference
In-Depth Information
Figure 5-2. The groupingBy collector
NOTE
You might be familiar with
group by
from using SQL; here we have a method with a
similar concept, but implemented in the idioms of the streams library.
Strings
A very common reason for collecting streams of data is to generate strings at the end. Let's
suppose that we want to put together a formatted list of names of the artists involved in an al-
bum. So, for example, if our input album is
Let It Be
, then we're expecting our output to look
like
"[George Harrison, John Lennon, Paul McCartney, Ringo Starr, The
Beatles]"
.
If we were to implement this before Java 8, we might have come up with something like
list. At each step, we pull out the names of the artists and add them to the
StringBuilder
.
Example 5-11. Formatting artist names using a for loop
StringBuilder builder
=
new
new
StringBuilder
(
"["
);
for
for
(
Artist artist
:
artists
) {
iif
(
builder
.
length
() >
1
)
builder
.
append
(
", "
);
String name
=
artist
.
getName
();
builder
.
append
(
name
);
}