Java Reference
In-Depth Information
ated to the StringCombiner.add method and the logic of combining two different combin-
ers is delegated to StringCombiner.merge . Let's take a look at these methods now, begin-
ning with the add method in Example 5-21 .
Example 5-21. The add method of a StringCombiner returns itself with a new element appen-
public StringCombiner add ( String element ) {
iif ( areAtStart ()) {
builder . append ( prefix );
} else
else {
builder . append ( delim );
builder . append ( element );
return this
this ;
add is implemented by delegating operations to an underlying StringBuilder instance. If
we're at the start of the combining operations, then we append our prefix; otherwise, we ap-
pend the string that fits between our elements (the delimiter). We follow this up by append-
ing the element. We return the StringCombiner object because this is the value that we're
pushing through our reduce operation. The merging code, provided in Example 5-22 , deleg-
ates to appending operations on the StringBuilder .
Example 5-22. The merge method of a StringCombiner combines the results of both
public StringCombiner merge ( StringCombiner other ) {
builder . append ( other . builder );
return this
this ;
We're nearly done with the reduce phase of refactoring, but there's one small step remain-
ing. We're going to inline the toString to the end of the method call chain so that our entire
sequence is method-chained. This is simply a matter of lining up the reduce code so that it's
ready to be converted into the Collector API (see Example 5-23 ) .
Example 5-23. Using a reduce and delegating to our custom StringCombiner
String result =
artists . stream ()
. map ( Artist: : getName )
. reduce ( new
new StringCombiner ( ", " , "[" , "]" ),
StringCombiner: : add ,
Search WWH ::

Custom Search