Java Reference
In-Depth Information
CaloricLevel.NORMAL;
else return CaloricLevel.FAT;
} ));
Now you've seen how to group the dishes in the menu, both by their type and by calories, but
what if you want to use both criteria at the same time? Grouping is powerful because it
composes effectively. Let's see how to do this.
6.3.1. Multilevel grouping
You can achieve multilevel grouping by using a collector created with a two-argument version of
the Collectors.groupingBy factory method, which accepts a second argument of type collector
besides the usual classification function. So to perform a two-level grouping, you can pass an
inner groupingBy to the outer groupingBy, defining a second-level criterion to classify the
stream's items, as shown in the next listing.
Listing 6.2. Multilevel grouping
The result of this two-level grouping is a two-level Map like the following:
{MEAT={DIET=[chicken], NORMAL=[beef], FAT=[pork]},
FISH={DIET=[prawns], NORMAL=[salmon]},
OTHER={DIET=[rice, seasonal fruit], NORMAL=[french fries, pizza]}}
Here the outer Map has as keys the values generated by the first-level classification function:
“fish, meat, other.” The values of this Map are in turn other Maps, having as keys the values
generated by the second-level classification function: “normal, diet, or fat.” Finally, the
second-level Maps have as values the List of the elements in the stream returning the
corresponding first- and second-level key values when applied respectively to the first and
second classification functions: “salmon, pizza, etc.” This multilevel grouping operation can be
 
Search WWH ::




Custom Search