I am looking for an implementation of group by, having and then filter based on count in lambda expressions.
select COUNT(employee_id), department_id from employee
GROUP BY department_id
HAVING COUNT(employee_id) > 1
Is there any simple implementation of achieving this using lambda expressions.
groupingBy. Returns a Collector implementing a cascaded "group by" operation on input elements of type T , grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector .
The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.
You can combine the groupingBy
collector, with counting()
and collectingAndThen
:
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
...
Map<Long, Long> map =
employees.stream()
.collect(collectingAndThen(groupingBy(Employee::getDeptId, counting()),
m -> { m.values().removeIf(v -> v <= 1L); return m; }));
Note that here is no guarantee on the mutability of the map returned by groupingBy
, so you can use the overloaded version and supply a concrete mutable instance if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With