How to sum multiple fields of a list of objects using stream in java

Viewed 40

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: Summing multiple different fields in a list of objects using the streams api? but I got syntax error. Here is my model:

public class BranchAccount {


    @NotNull(message = "Account balance is required")
    private Double accountBalance;

    @NotNull(message = "Profit is required")
    private Double profit;


    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated;

    @Temporal(TemporalType.TIMESTAMP)
    private Date lastUpdated;
}

My Pojo:

public class ProfitBalanceDto {

   private Double accountBalance;

   private Double profit;

}

My code to get sum of accountBalance and profit from BranchAccount:

public ProfitBalanceDto getAllBranchAccount() {
    List<BranchAccount> branchAccounts = branchAccountRepository.findAll();
            branchAccounts.stream()
            .reduce(new ProfitBalanceDto(0.0, 0.0), (branchAccount1, branchAccount2) -> {
                return new ProfitBalanceDto(
                        branchAccount1.getAccountBalance() + branchAccount2.getAccountBalance(),
                        branchAccount1.getProfit() + branchAccount2.getProfit());
            });

return null;
}

My errors: enter image description here

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

1 Answers

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