Java 9 stream enhancement with Collectors.filtering method with a stream. Its basic requirements while Grouping with filtering. Let see one example with Java 8 so we can get more advantages of Collectors.filtering advantages. Here is an example of Java 9 Collectors Filtering Example.

Java 8: GroupingBy + Filter

Here is some limitation if salary less than 1000 than those key and value both will be removed so in

java.util.Map<String, Long> employeeGroup =
 .filter(employee -> employee.getSalary()>1_000)                                 // it will filter Sr. Developer because there are no record in greater than 1000

employeeGroup.forEach((k, v) -> {
 System.out.println(k + "-" + v);




Java 9 : GroupingBy + Collectors.filtering

Collectors.filtering will not consider value but it will consider key with 0 counts, If a value contains List than it will contain Empty List if predicate will not be satisfied consider. Means that Collectors.filtering will return group by key with 0 or empty data value if the filter will discard record that grouped value.

java.util.Map<String, Long> employeeGroup =
                                .collect(Collectors.groupingBy(Employee::getDesignation, Collectors.filtering(e -> {
                                    return e.getSalary() > 1_000;                   // it will collect Sr. Developer with 0 count
                                }, Collectors.counting())));


Sr. Developer-0


Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.

Leave a Reply

Your email address will not be published. Required fields are marked *