Java Reference
In-Depth Information
which, as expected, will generate
pork, beef, chicken, french fries, rice, season fruit, pizza, prawns, salmon
Until now, we've explored various collectors that reduce a stream to a single value. In the next
section, we demonstrate how all the reduction processes of this form are special cases of the
more general reduction collector provided by the Collectors.reducing factory method.
6.2.4. Generalized summarization with reduction
All the collectors we've discussed so far are, in reality, only convenient specializations of a
reduction process that can be defined using the reducing factory method. The
Collectors.reducing factory method is a generalization of all of them. The special cases discussed
earlier are arguably provided only for programmer convenience. (But remember that
programmer convenience and readability are of prime importance!) For instance, it's possible to
calculate the total calories in your menu with a collector created from the reducing method as
follows:
int totalCalories = menu.stream().collect(reducing(
0, Dish::getCalories, (i, j) -> i + j));
It takes three arguments:
The first argument is the starting value of the reduction operation and will also be the value returned
in the case of a stream with no elements, so clearly 0 is the appropriate value in the case of a numeric
sum.
The second argument is the same function you used in section 6.2.2 to transform a dish into an int
representing its calorie content.
The third argument is a BinaryOperator that aggregates two items into a single value of the same
type. Here, it just sums two int s.
Similarly, you could find the highest-calorie dish using the one-argument version of reducing as
follows:
Optional<Dish> mostCalorieDish =
menu.stream().collect(reducing(
(d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2));
You can think of the collector created with the one-argument reducing factory method as a
particular case of the three-argument method, which uses the first item in the stream as a
 
Search WWH ::




Custom Search