Java Reference
In-Depth Information
stream. Here you create a Comparator comparing dishes based on their calorie content and pass
it to Collectors.maxBy:
Comparator<Dish> dishCaloriesComparator =
Comparator.comparingInt(Dish::getCalories);
Optional<Dish> mostCalorieDish =
menu.stream()
.collect(maxBy(dishCaloriesComparator));
You may wonder what the Optional<Dish> is about. To answer this we need to ask the
question ”What if menu were empty?” There's no dish to return! Java 8 introduces Optional,
which is a container that may or may not contain a value. Here it perfectly represents the idea
that there may or may not be a dish returned. We briefly mentioned it in
chapter 5
when you
encountered the method findAny. Don't worry about it for now; we devote
chapter 10
to the
study of Optional<T> and its operations.
Another common reduction operation that returns a single value is to sum the values of a
numeric field of the objects in a stream. Alternatively, you may want to average the values. Such
operations are called
summarization
operations. Let's see how you can express them using
collectors.
6.2.2. Summarization
The Collectors class provides a specific factory method for summing: Collectors .summingInt. It
accepts a function that maps an object into the int that has to be summed and returns a collector
that, when passed to the usual collect method, performs the requested summarization. So, for
instance, you can find the total number of calories in your menu list with
int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
Here the collection process proceeds as illustrated in
figure 6.2
. While traversing the stream
each dish is mapped into its number of calories, and this number is added to an accumulator
starting from an initial value (in this case the value is 0).
Search WWH ::
Custom Search