Java 9 stream enhancement with Collectors.filtering method with stream. It 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 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 =
 employeeList.stream()
 .filter(employee -> employee.getSalary()>1_000)                                 // it will filter Sr. Developer because there are no record in greater than 1000
 .collect(Collectors.groupingBy(Employee::getDesignation,Collectors.counting()));

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

});

Output:

Developer-1
CEO-1

Java 9 : GroupingBy + Collectors.filtering

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

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

Output:

Sr. Developer-0
Developer-1
CEO-1

 

Tags:

Leave a Reply

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