00:00

Collectors.filtering() in Java

Last updated:

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

Collectors.java (API)
// java.util.stream.Collectors (Java 9)
static <T, A, R> Collector<T, ?, R> filtering(
        Predicate<? super T> predicate,
        Collector<? super T, A, R> downstream)
Usage
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.

Filtering before grouping compared with filtering() inside grouping Left: filter first, then groupingBy. Cities with no matching orders disappear from the map. Right: groupingBy with filtering as the downstream collector. Every city that has orders appears, and cities without matches show an empty list or a zero count. filter(...) then groupingBy(...) elements removed before grouping groups without matches vanish Kochi missing from the map Java 8 compatible groupingBy(..., filtering(...)) elements grouped first then filtered inside each group Kochi=0 stays in the map Java 9 and later VS
Figure 1: The order of grouping and filtering decides whether empty groups survive.

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.

LargeOrdersPerCity.java
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);
    }
}
Output
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.

OnLeavePerTeam.java
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)));
    }
}
Output
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.

StockByCategory.java
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"));
    }
}
Output
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()

ApproachGroups with zero matchesSince
filter(p).collect(groupingBy(k))MissingJava 8
collect(groupingBy(k, filtering(p, c)))Present, emptyJava 9
partitioningBy(p)Both true and false always presentJava 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

Note
// 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 where filter() 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