3

How to groupby one field and sum the other two fields? The class Salary is as following:

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 groupby the id and sum both the simSalary and the nonsimSalary, the result should be like:

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

However using the following code, I could only sum one field, how to sum both of the two fields at one time?

List<Salary> salaryList = getSalary();
salaryList.stream().collect(Collectors.groupingBy(Salary::getId,
            Collectors.summingDouble(Salary::getSimSalary))));
Jordan Lewis
  • 16,900
  • 4
  • 29
  • 46
QSY
  • 127
  • 1
  • 8
  • I’m sure it’s a duplicate. Where did we put the other questions to the same? – Ole V.V. Apr 12 '17 at 12:24
  • Hej i København! There’s a good one here: [Group by and sum objects like in SQL with Java lambdas?](http://stackoverflow.com/questions/26340688/group-by-and-sum-objects-like-in-sql-with-java-lambdas) See if it doesn’t solve your problem. There are others, so go searching. And BTW, always try searching for an answer before posting your question; chances are you will find the answer faster that way. – Ole V.V. Apr 12 '17 at 12:34

0 Answers0