Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of having count with group by in java 8

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.

like image 447
Patan Avatar asked Mar 28 '16 11:03

Patan


People also ask

How does Collector groupingBy work?

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 .

Is there a count method in Java?

The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.


1 Answers

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.

like image 152
Alexis C. Avatar answered Sep 25 '22 09:09

Alexis C.