Collectors.filtering() in Java
Collectors.filtering() is a static method added to java.util.stream.Collectors in Java 9. It adapts a downstream collector so that only elements matching a Predicate are collected. It is the collector version of Stream.filter().
Its key difference from filtering before grouping: groups whose elements are all rejected still appear in the result, with an empty value. That makes it ideal for reports that must list every category, even those with zero matches.
1. Syntax and Method Signature
// java.util.stream.Collectors (Java 9)
static <T, A, R> Collector<T, ?, R> filtering(
Predicate<? super T> predicate,
Collector<? super T, A, R> downstream)
Map<String, Long> highValuePerCity = orders.stream()
.collect(Collectors.groupingBy(Order::city,
Collectors.filtering(o -> o.total() > 5_000, Collectors.counting())));
2. How filtering() Works
The filtering() collector tests each element it receives and passes only matching elements to the downstream accumulator. When used inside groupingBy(), the element has already been assigned to its group, so the group's container is created even if every element in it is then rejected.
At the top level, stream.filter(p).collect(c) is equivalent and clearer. Use filtering() when you need the filter to run after grouping.
3. Java Examples
Example 1: Keeping groups with zero matches (Java 16+)
Count large orders per city, showing every city that has any order at all.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class LargeOrdersPerCity {
record Order(String city, int total) { }
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("Pune", 8200), new Order("Kochi", 900), new Order("Pune", 1200),
new Order("Agra", 6400), new Order("Kochi", 450));
Map<String, Long> filterFirst = orders.stream()
.filter(o -> o.total() > 5000)
.collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.counting()));
Map<String, Long> filterInside = orders.stream()
.collect(Collectors.groupingBy(Order::city, TreeMap::new,
Collectors.filtering(o -> o.total() > 5000, Collectors.counting())));
System.out.println("filter() first: " + filterFirst);
System.out.println("filtering() inside: " + filterInside);
}
}
filter() first: {Agra=1, Pune=1}
filtering() inside: {Agra=1, Kochi=0, Pune=1}
How it works: Filtering first removes Kochi's orders before grouping, so Kochi disappears. With filtering() inside the grouping, Kochi stays with a count of 0, which is what a report usually needs.
Example 2: Filtered lists per group (Java 16+)
For each team, list the members who are on leave today.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class OnLeavePerTeam {
record Member(String name, String team, boolean onLeave) { }
public static void main(String[] args) {
List<Member> members = List.of(
new Member("Aditi", "Web", true), new Member("Bhuvan", "Web", false),
new Member("Chetan", "Mobile", false), new Member("Divya", "Mobile", false),
new Member("Eshita", "QA", true));
Map<String, List<String>> onLeave = members.stream()
.collect(Collectors.groupingBy(Member::team, TreeMap::new,
Collectors.filtering(Member::onLeave,
Collectors.mapping(Member::name, Collectors.toList()))));
onLeave.forEach((team, names) -> System.out.println(team + ": " + (names.isEmpty() ? "everyone in" : names)));
}
}
Mobile: everyone in QA: [Eshita] Web: [Aditi]
How it works: Collectors can be nested: filtering() keeps members on leave, and mapping() keeps only their names. The Mobile team appears with an empty list, which the program turns into a friendly message.
Example 3: Two different filters in one pass (Java 16+)
For each product category, count all products and the out-of-stock ones.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class StockByCategory {
record Product(String category, int stock) { }
public static void main(String[] args) {
List<Product> products = List.of(
new Product("Audio", 4), new Product("Audio", 0), new Product("Video", 12),
new Product("Audio", 0), new Product("Video", 3));
Map<String, Long> total = products.stream()
.collect(Collectors.groupingBy(Product::category, TreeMap::new, Collectors.counting()));
Map<String, Long> outOfStock = products.stream()
.collect(Collectors.groupingBy(Product::category, TreeMap::new,
Collectors.filtering(p -> p.stock() == 0, Collectors.counting())));
total.forEach((category, n) -> System.out.println(category + ": " + outOfStock.get(category) + " of " + n + " out of stock"));
}
}
Audio: 2 of 3 out of stock Video: 0 of 2 out of stock
How it works: Because filtering() keeps every category, outOfStock.get(category) never returns null, so the two maps line up without extra checks.
4. Real-World Use Cases
- Complete reports: counts or totals per category, including categories with zero matches.
- Dashboards: overdue tasks per team, where every team must be listed.
- Aligned maps: several filtered statistics with the same keys, ready to display side by side.
5. Important Points
- Java 9 or later is required.
- Groups come from all elements: only groups that have at least one element appear; categories absent from the data are still missing.
- Empty values: rejected groups hold an empty list, 0 count or the downstream collector's empty result.
- Top level: prefer
filter()outside of other collectors. - Performance: grouping all elements first costs slightly more than filtering first; it is the price of keeping empty groups.
6. filtering() vs filter() and partitioningBy()
| Approach | Groups with zero matches | Since |
|---|---|---|
filter(p).collect(groupingBy(k)) | Missing | Java 8 |
collect(groupingBy(k, filtering(p, c))) | Present, empty | Java 9 |
partitioningBy(p) | Both true and false always present | Java 8 |
Its siblings are mapping() and flatMapping().
7. Common Mistakes and Best Practices
Expecting filter() before grouping to keep empty groups
As Example 1 shows, filtering first removes whole groups. If a report must list every group, filter inside with filtering().
Expecting categories that never occur to appear
// filtering() cannot create a "Drones" group if no product has that category at all
Pre-fill a map with every known category, as shown on the counting() page.
Other mistakes to avoid
- Using
filtering()at the top level wherefilter()reads better. - Writing complex predicates inline inside nested collectors.
- Using it on Java 8. It was added in Java 9.
8. Summary
filtering()(Java 9) filters elements inside another collector.- Inside
groupingBy(), it keeps groups that have no matches, with empty results. - Filtering before grouping removes those groups instead.
- At the top level, prefer
filter().
9. References
Frequently Asked Questions (FAQ)
Q1. What does Collectors.filtering() do?
filtering(), added in Java 9, adapts a downstream collector so that only elements matching a predicate are collected. It is the collector version of filter().
Q2. What is the difference between filter() before groupingBy() and filtering() inside it?
Filtering first removes elements before grouping, so groups with no matching elements disappear. filtering() inside groupingBy() groups first, so those groups remain with an empty result, such as an empty list or a count of 0.
Q3. When should I use Collectors.filtering()?
Use it inside groupingBy() or partitioningBy() when every group must appear in the result, for example in reports that show zero counts.
Q4. Is filtering() available in Java 8?
No. It was added in Java 9, together with flatMapping().
Q5. Can filtering() be combined with other collectors?
Yes. Its downstream collector can be any collector, such as counting(), toList(), mapping() or summingInt().