How to group by one field and sum two other fields

How can I group one field and sum the other two? The Salary class looks like this:

public class Salary {
  private Integer id;   
  private Double simSalary;
  private Double nonsimSalary;
}

      

the data is like:

id = 01, simSalary = 100, nonsimSalary = 0;
id = 01, simSalary = 0, nonsimSalary = 20;
id = 02, simSalary =50, nonsimSalary = 30;

      

I want to group the id and sum both simSalary and nonsimSalary, the result should look like this:

id = 01, simSalary = 100, nonsimSalary = 20;
id = 02, simSalary = 50, nonsimSalary = 30;

      

However, using the following code I could only sum one field, how can I sum both of these fields in one go?

List<Salary> salaryList = getSalary();
salaryList.stream().collect(Collectors.groupingBy(Salary::getId,
            Collectors.summingDouble(Salary::getSimSalary))));

      

+3


source to share





All Articles