Java Reference
In-Depth Information
StringCombiner:
:
merge
)
.
toString
();
At this stage, we have some code that looks vaguely sane, but it's quite hard to reuse this
same combining operation in different parts of our code base. So we're going to refactor our
reduce
operation into a
Collector
, which we can use anywhere in our application. I've
called our
Collector
the
StringCollector
. Let's refactor our code to use it in
Example 5-24. Collecting strings using a custom StringCollector
String result
=
artists
.
stream
()
.
map
(
Artist:
:
getName
)
.
collect
(
new
new
StringCollector
(
", "
,
"["
,
"]"
));
Now that we're delegating the whole of the
String
-joining behavior to a custom collector,
our application code doesn't need to understand anything about the internals of
StringCol-
lector
. It's just another
Collector
like any in the core framework.
so we need to determine a few types to interact with:
▪ The type of the element that we'll be collecting, a
String
▪ Our accumulator type,
StringCombiner
, which you've already seen
▪ The result type, also a
String
Example 5-25. How to define a collector over strings
public
public class
class
StringCollector
StringCollector
implements
implements
Collector
<
String
,
StringCombiner
,
String
> {
A
Collector
is composed of four different components. First we have a
supplier
, which is
a factory for making our container—in this case, a
StringCombiner
. The analogue to this is
the first argument provided to the
reduce
operation, which was the initial value of the
re-
duce
(see
Example 5-26
)
.
Example 5-26. A supplier is a factory for making our container
public
public
Supplier
<
StringCombiner
>
supplier
() {
return
return
() ->
new
new
StringCombiner
(
delim
,
prefix
,
suffix
);
}