我正在嘗試從 Model 類中獲取兩個欄位的總和。并使用 pojo 將其回傳,但不斷出現語法錯誤。我要實作的目標類似于此中投票最高的答案:
請問我做錯了嗎?
PS:我想為此使用流。
uj5u.com熱心網友回復:
正如@Holger 在他的評論中提到的那樣,您可以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));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/508298.html
