如何使用java中的流对对象列表的多个字段求和

Bil*_*abo 1 java-8 spring-data-jpa spring-boot java-stream

我试图从模型类中获取两个字段的总和。并使用 pojo 返回它,但不断出现语法错误。我想要实现的目标类似于此中得票最高的答案:使用流 API 对对象列表中的多个不同字段求和?但我遇到语法错误。这是我的模型:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的波乔:

public class ProfitBalanceDto {

   private Double accountBalance;

   private Double profit;

}
Run Code Online (Sandbox Code Playgroud)

我从 BranchAccount 获取 accountBalance 和利润总和的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的错误: 在此输入图像描述

请问我做错了吗?
PS:我想为此使用流。

Eri*_*ean 6

ProfitBalanceDto正如@Holger 在他的评论中提到的,你可以在减少之前映射到

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()));
}
Run Code Online (Sandbox Code Playgroud)

如果您使用 Java 12 或更高版本,那么使用 teeing 收集器可能是更好的选择

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