Home > Software design >  How to sum multiple fields of a list of objects using stream in java
How to sum multiple fields of a list of objects using stream in java

Time:09-14

I'm trying to get the sums of two fields from a Model class. and return it using using a pojo but kept getting syntax errors. What I am trying to achieve is similar to the highest voted answer in This: enter image description here

Please am I doing wrong?
PS: I want to use stream for this.

CodePudding user response:

As @Holger mentioned in his comment, you can map to ProfitBalanceDto before reducing

public ProfitBalanceDto getAllBranchAccount2() {
    List<BranchAccount> branchAccounts = branchAccountRepository.findAll();
    return branchAccounts.stream()
                         .map(acc -> new ProfitBalanceDto(acc.getAccountBalance(), acc.getProfit()))
                         .reduce(new ProfitBalanceDto(0.0, 0.0),
                                 (prof1, prof2) -> new ProfitBalanceDto(prof1.getAccountBalance()  prof2.getAccountBalance(),
                                                                        prof1.getProfit()   prof2.getProfit()));
}

If you are using Java 12 or higher using the teeing collector might be a better option

public ProfitBalanceDto getAllBranchAccount() {
    List<BranchAccount> branchAccounts = branchAccountRepository.findAll();
    return branchAccounts.stream()
                         .collect(Collectors.teeing(
                                 Collectors.summingDouble(BranchAccount::getAccountBalance),
                                 Collectors.summingDouble(BranchAccount::getProfit),
                                 ProfitBalanceDto::new));
}
  • Related