September 2019
Intermediate to advanced
816 pages
18h 47m
English
User problem: I want to take all the melons that are heavier than 2,000 g and group them by their type. For each type, add them to the proper container (there is a container for each type – just check the container's labels).
By using filtering(Predicate<? super T> predicate, Collector<? super T,A,R> downstream), we apply a predicate to each element of the current collector and accumulate the output in the downstream collector.
So, to group the melons that are heavier than 2,000 g by type, we can write the following stream pipeline:
Map<String, Set<Melon>> melonsFiltering = melons.stream() .collect(groupingBy(Melon::getType, filtering(m -> m.getWeight() > 2000, toSet())));
The output will be as follows (each Set<Melon> is a ...