小编Bil*_*abo的帖子

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

我试图从模型类中获取两个字段的总和。并使用 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());
            }); …
Run Code Online (Sandbox Code Playgroud)

java-8 spring-data-jpa spring-boot java-stream

1
推荐指数
1
解决办法
976
查看次数