Grouping by adding two BigDecimal type attributes of a class

Vimal :

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]

Grzegorz Piwowarek :

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}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73298&siteId=1
Recommended