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; }));
Please note that there is no guarantee on the volatility of the map returned by groupingBy
, so you can use the overloaded version and provide a specific mutable instance if you want.
source share