spring-data-jpa 如何在java中使用stream对对象列表的多个字段求和

aydmsdu9  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(173)

我试图从一个Model类中得到两个字段的和。并使用pojo返回它,但一直得到语法错误。我试图实现的类似于This中投票最多的答案:Summing multiple different fields in a list of objects using the streams 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;
}

我的Pojo:

public class ProfitBalanceDto {

   private Double accountBalance;

   private Double profit;

}

我的代码,以获得帐户余额和利润的总和从分行帐户:

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;
}

我的错误:

拜托我做错了吗?
PS:我想用流来做这个。

r55awzrz

r55awzrz1#

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

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()));
}

如果您使用的是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));
}

相关问题