Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping by adding two BigDecimal type attributes of a class

I want sum of two BigDecimal type attributes of the same class and grouping them with some other attribute of the class.

I tried using Collectors.groupingBy() and Collectors.reducing() method but this is applicable for only one attribute that can be summed up.

Employee class has below attributes:

class Employee{
 private String name;
 private BigDecimal salary;
 private BigDecimal bonus;
 private String department;

 // Getters and Setters
 }

employeeList.stream().collect(Collectors.groupingBy(
                              Employee::getDepartment, Collectors.reducing(
                                        BigDecimal.ZERO, 
                    (id, emp) -> id.add(emp.getSalary().add(emp.getBonus)), 
                                         BigDecimal::add)));

As per the last piece of the code, Collectors.reducing() I want sum of Salary and Bonus that will be grouped along with the respective departments. For example,

Department A -

Employee 1- Salary 1000, Bonus 100

Employee 2- Salary 2000, Bonus 100

Department B -

Employee 3 - Salary 5000, Bonus 100

Now I want a map like below:

[Department-A, 3200],[Department-b, 5100]

like image 556
Vimal Avatar asked Jan 02 '23 10:01

Vimal


1 Answers

In order to achieve that effect, you need to combine two separate Collectors: groupingBy() and reducing():

Map<String, BigDecimal> result = employeeList.stream()
      .collect(Collectors
        .groupingBy(Employee::getDepartment, Collectors
          .reducing(BigDecimal.ZERO, e -> e.getBonus().add(e.getSalary()), BigDecimal::add)));

output: {DepartmentB=5100, DepartmentA=3200}

like image 58
Grzegorz Piwowarek Avatar answered Jan 05 '23 16:01

Grzegorz Piwowarek