Java Reference
In-Depth Information
List<Dish> vegetarianDishes = partitionedMenu.get(true);
Note that you could achieve the same result by just filtering the stream created from the menu
List with the same predicate used for partitioning and then collecting the result in an additional
List:
List<Dish> vegetarianDishes =
menu.stream().filter(Dish::isVegetarian).collect(toList());
6.4.1. Advantages of partitioning
Partitioning has the advantage of keeping both lists of the stream elements, for which the
application of the partitioning function returns true or false. So in the previous example, you can
obtain the List of the nonvegetarian Dishes by accessing the value of the key false in the
partitionedMenu Map, using two separate filtering operations: one with the predicate and one
with its negation. Also, as you already saw for grouping, the partitioningBy factory method has
an overloaded version to which you can pass a second collector, as shown here:
This will produce a two-level Map:
{false={FISH=[prawns, salmon], MEAT=[pork, beef, chicken]},
true={OTHER=[french fries, rice, season fruit, pizza]}}
Here the grouping of the dishes by their type is applied individually to both of the substreams of
vegetarian and nonvegetarian dishes resulting from the partitioning, producing a two-level Map
that's similar to the one you obtained when you performed the two-level grouping in section
6.3.1 . As another example, you can reuse your earlier code to find the most caloric dish among
both vegetarian and nonvegetarian dishes:
Map<Boolean, Dish> mostCaloricPartitionedByVegetarian =
menu.stream().collect(
partitioningBy(Dish::isVegetarian,
collectingAndThen(
maxBy(comparingInt(Dish::getCalories)),
Optional::get)));
 
Search WWH ::




Custom Search