Java Reference
In-Depth Information
collector will then be used to collect the elements in each substream generated by the grouping
function, allowing you to obtain as a result the following Map:
{OTHER=[DIET, NORMAL], MEAT=[DIET, NORMAL, FAT], FISH=[DIET, NORMAL]}
From this you can easily figure out your choices. If you're in the mood for fish and you're on a
diet, you could easily find a dish; likewise, if you're very hungry and want something with lots of
calories, you could satisfy your robust appetite by choosing something from the meat section of
the menu. Note that in the previous example, there are no guarantees about what type of Set is
returned. But by using toCollection, you can have more control. For example, you can ask for a
HashSet by passing a constructor reference to it:
Map<Dish.Type, Set<CaloricLevel>> caloricLevelsByType =
menu.stream().collect(
groupingBy(Dish::getType, mapping(
dish -> { if (dish.getCalories() <= 400) return CaloricLevel.DIET;
else if (dish.getCalories() <= 700) return CaloricLevel.NORMAL;
else return CaloricLevel.FAT; },
toCollection(HashSet::new) )));
6.4. Partitioning
Partitioning is a special case of grouping: having a predicate (a function returning a boolean),
called a partitioning function , as a classification function. The fact that the partitioning function
returns a boolean means the resulting grouping Map will have a Boolean as a key type and
therefore there can be at most two different groups—one for true and one for false. For instance,
if you're vegetarian or have invited a vegetarian friend to have dinner with you, you may be
interested in partitioning the menu into vegetarian and nonvegetarian dishes:
This will return the following Map:
{false=[pork, beef, chicken, prawns, salmon],
true=[french fries, rice, season fruit, pizza]}
So you could retrieve all the vegetarian dishes by getting from this Map the value indexed with
the key true:
 
Search WWH ::




Custom Search