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]
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With