7

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.

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.