Java Reference
In-Depth Information
6.2. Reducing and summarizing
To illustrate the range of possible collector instances that can be created from the Collectors
factory class, we'll reuse the domain we introduced in the previous chapter: a menu consisting of
a list of delicious dishes!
As you just learned, collectors (the parameters to the Stream method collect) are typically used
in cases where it's necessary to reorganize the stream's items into a collection. But more
generally, they can be used every time you want to combine all the items in the stream into a
single result. This result can be of any type, as complex as a multilevel map representing a tree
or as simple as a single integer—perhaps representing the sum of all the calories in the menu.
We'll look at both of these result types: single integers in section 6.2.2 and multilevel grouping
in section 6.3.1 .
As a first simple example, let's count the number of dishes in the menu, using the collector
returned by the counting factory method:
long howManyDishes = menu.stream().collect(Collectors.counting());
You can write this far more directly as
long howManyDishes = menu.stream().count();
but the counting collector can be especially useful when used in combination with other
collectors, as we demonstrate later.
In the rest of this chapter, we assume that you've imported all the static factory methods of the
Collectors class with
import static java.util.stream.Collectors.*;
so you can write counting() instead of Collectors.counting() and so on.
Let's continue exploring simple predefined collectors by looking at how you can find the
maximum and minimum values in a stream.
6.2.1. Finding maximum and minimum in a stream of values
Suppose you want to find the highest-calorie dish in the menu. You can use two collectors,
Collectors.maxBy and Collectors.minBy, to calculate the maximum or minimum value in a
stream. These two collectors take a Comparator as argument to compare the elements in the
 
Search WWH ::




Custom Search