Skip to content
Advertisement

Aggregate multiple fields grouping by multiple fields in Java 8

In the Employee class below, I would like to get average salary, average bonus and average perks for all employees grouping by department, designation and gender and would like the result to be a List<Employee> with the aggregated values for salary, bonus and perks.

JavaScript

What would be a clean way of doing that?

Advertisement

Answer

You can do this by creating a class for the grouping key and writing a collector:

I’m simply ading the values per key and count the occurances in a map. In the finisher I devide the sums through the count.

You could get rid of the countMap by sublassing Employee, adding the count and using this class for the supplier/subtotal and using some casting…

You could also make to groupBys one for the sum and another for the count and computing the avarages with the two created maps…

JavaScript

Class for the aggregating key

JavaScript

Collector

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement