Java Reference
In-Depth Information
collector—but it is quite an instructive example both of how custom collectors work and of
how to refactor legacy code into Java 8.
Example 5-17. Using a for loop and a StringBuilder to pretty-print the names of artists
StringBuilder builder
=
new
new
StringBuilder
(
"["
);
for
for
(
Artist artist
:
artists
) {
iif
(
builder
.
length
() >
1
)
builder
.
append
(
", "
);
String name
=
artist
.
getName
();
builder
.
append
(
name
);
}
builder
.
append
(
"]"
);
String result
=
builder
.
toString
();
It's pretty obvious that we can use the
map
operation to transform the
Stream
of artists into a
Example 5-18. Using a forEach and a StringBuilder to pretty-print the names of artists
StringBuilder builder
=
new
new
StringBuilder
(
"["
);
artists
.
stream
()
.
map
(
Artist:
:
getName
)
.
forEach
(
name
-> {
iif
(
builder
.
length
() >
1
)
builder
.
append
(
", "
);
builder
.
append
(
name
);
});
builder
.
append
(
"]"
);
String result
=
builder
.
toString
();
This has made things a bit clearer in the sense that the mapping to names shows us what has
been built up a bit more quickly. Unfortunately, there's still this very large
forEach
block
that doesn't fit into our goal of writing code that is easy to understand by composing high-
level operations.
Let's put aside our goal of building a custom collector for a moment and just think in terms
of the existing operations that we have on streams. The operation that most closely matches
what we're doing in terms of building up a
String
is the
reduce
operation. Refactoring
Example 5-18
to use that results in
Example 5-19
.