Java Reference
In-Depth Information
Collection framework flexibility: doing the same operation in different
ways
You can further simplify the previous sum example using the reducing collector by using a
reference to the sum method of the Integer class instead of the lambda expression you used to
encode the same operation. This results in the following:
Logically, this reduction operation proceeds as shown in figure 6.3 , where an accumulator,
initialized with a starting value, is iteratively combined, using an aggregating function, with the
result of the application of the transforming function on each element of the stream.
Figure 6.3. The reduction process calculating the total number of
calories in the menu
The counting collector we mentioned at the beginning of section 6.2 is, in reality, similarly
implemented using the three-argument reducing factory method. It transforms each element in
the stream to an object of type Long with value 1 and then sums all these ones:
public static <T> Collector<T, ? , Long> counting() {
return reducing(0L, e -> 1L, Long::sum);
 
Search WWH ::




Custom Search