Java Reference
In-Depth Information
Adapting the collector result to a different type
Because the Optionals wrapping all the values in the Map resulting from the last grouping
operation aren't very useful in this case, you may want to get rid of them. To achieve this, or
more generally, to adapt the result returned by a collector to a different type, you could use the
collector returned by the Collectors.collectingAndThen factory method, as shown in the
following listing.
Listing 6.3. Finding the highest-calorie Dish in each subgroup
This factory method takes two arguments, the collector to be adapted and a transformation
function, and returns another collector. This additional collector acts as a wrapper for the old
one and maps the value it returns using the transformation function as the last step of the collect
operation. In this case, the wrapped collector is the one created with maxBy, and the
transformation function, Optional::get, extracts the value contained in the Optional returned. As
we've said, here this is safe because the reducing collector will never return an Optional.empty().
The result is the following Map:
{FISH=salmon, OTHER=pizza, MEAT=pork}
It's quite common to use multiple nested collectors, and at first the way they interact may not
always be obvious. Figure 6.6 helps you visualize how they work together. From the outermost
layer and moving inward, note the following:
 
Search WWH ::




Custom Search