filtering as a Downstream Collector
What you'll learn: How to apply Collectors.filtering() to selectively include elements within grouped or partitioned results, combining filtering logic with grouping operations.
The Core Idea
You've already used filter() on streams to remove unwanted elements before collecting. But what if you want to filter after grouping? That's where Collectors.filtering() comes in.
This downstream collector lets you apply a predicate to elements within each group, keeping only those that match. Think of it like organizing books by genre, but within each genre only keeping books published after 2020.
Why Use filtering as a Downstream Collector?
When you group data with groupingBy() or partition with partitioningBy(), you sometimes need to filter elements within each group. Without Collectors.filtering(), you'd filter before grouping—which might change your group structure or lose empty groups entirely.
How It Works
The signature looks like:
Collectors.filtering(Predicate<T> predicate, Collector<T,A,R> downstream)
The predicate determines which elements to keep, and the downstream collector processes the filtered elements (like toList(), counting(), etc.).
Example Pattern
Imagine grouping people by city, but only counting adults (18+) in each city:
Map<String, Long> adultsByCity = people.stream()
.collect(groupingBy(
Person::getCity,
filtering(p -> p.getAge() >= 18, counting())
));
Without filtering(), you'd have to filter before grouping, which might exclude entire cities from your result map.
Key Takeaway: Collectors.filtering() applies a predicate to elements within each group, allowing selective inclusion without affecting the group structure itself—essential for precise downstream transformations.