Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

filtering()

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content