Java Reference
In-Depth Information
{FISH=[prawns, salmon], OTHER=[french fries, rice, season fruit, pizza],
MEAT=[pork, beef, chicken]}
Here, you pass to the groupingBy method a Function (expressed in the form of a method
reference) extracting the corresponding Dish.Type for each Dish in the stream. We call this
Function a classification function because it's used to classify the elements of the stream into
different groups. The result of this grouping operation, shown in figure 6.4 , is a Map having as
map key the value returned by the classification function and as corresponding map value a list
of all the items in the stream having that classified value. In the menu-classification example a
key is the type of dish, and its value is a list containing all the dishes of that type.
Figure 6.4. Classification of an item in the stream during the grouping
process
But it isn't always possible to use a method reference as a classification function, because you
may wish to classify using something more complex than a simple property accessor. For
instance, you could decide to classify as “diet” all dishes with 400 calories or fewer, set to
“normal” the dishes having between 400 and 700 calories, and set to “fat” the ones with more
than 700 calories. Because the author of the Dish class unhelpfully didn't provide such an
operation as a method, you can't use a method reference in this case, but you can express this
logic in a lambda expression:
public enum CaloricLevel { DIET, NORMAL, FAT }
Map<CaloricLevel, List<Dish>> dishesByCaloricLevel = menu.stream().collect(
groupingBy(dish -> {
if (dish.getCalories() <= 400) return CaloricLevel.DIET;
else if (dish.getCalories() <= 700) return
 
Search WWH ::




Custom Search