Java Reference
In-Depth Information
That will produce the following result:
{false=pork, true=pizza}
We started this section by saying that you can think of partitioning as a special case of grouping.
The analogies between the groupingBy and partitioningBy collectors don't end here; as you'll see
in the next quiz, you can also perform multilevel partitioning in a way similar to what you did
for grouping in section 6.3.1 .
Quiz 6.2: Using partitioningBy
As you've seen, like the groupingBy collector, the partitioningBy collector can be used in
combination with other collectors. In particular it could be used with a second partitioningBy
collector to achieve a multilevel partitioning. What will be the result of the following multilevel
partitionings?
1 .
menu.stream().collect(partitioningBy(Dish::isVegetarian,
partitioningBy(d -> d.getCalories() > 500)));
2 .
menu.stream().collect(partitioningBy(Dish::isVegetarian,
partitioningBy(Dish::getType)));
3 .
menu.stream().collect(partitioningBy(Dish::isVegetarian,
counting()));
Answer:
1 . This is a valid multilevel partitioning, producing the following two-level Map:
{ false={false=[chicken, prawns, salmon], true=[pork, beef]},
true={false=[rice, season fruit], true=[french fries, pizza]}}
2 . This won't compile because partitioningBy requires a predicate, a function returning a
boolean. And the method reference Dish::getType can't be used as a predicate.
Search WWH ::




Custom Search