Collectors filtering method was added to Java 9 and is similar in a way to the Stream filter method. But whereas the Stream filter method is used for filtering streams, the collectors filtering method is intended to be used with the collectors groupingBy
method.
Let’s look at an example of using the collectors filtering method with the groupingBy method. Let’s say we want to return the number of occurrences of even numbers in a list.
1 2 3 4 5 6 7 8 9 | public static void countEventNumbers() {
List<Integer> numbersList = List.of(1, 2, 3, 4, 4, 5);
Map<Integer, Long> countOfEvenNumbersMap = numbersList.stream().collect(
Collectors.groupingBy(i -> i,
Collectors.filtering(val -> val % 2 == 0, Collectors.counting())));
System.out.println(countOfEvenNumbersMap);
}
|
If we execute the above code we will get the output:
1 | {1=0, 2=1, 3=0, 4=2, 5=0}
|
As we can see the filtering method takes a function for filtering the input elements and a collector to collect the filtered elements.
1 | Collectors.filtering(val -> val % 2 == 0, Collectors.counting())
|
In this tutorial we looked at the Collectors.filtering
method that was added in Java 9. We also mentioned that this method is intended to be used with the Collectors.groupingBy
method.