你有两个类:
Account: number: String, balance: Long
Transaction: uuid: String, sum: Long, account: Account
对于具有相应名称(getNumber()、getSum()、getAccount() 等)的所有字段,这两个类都有 getter。
我需要计算每个账户的交易总和,但不是按账户计算,而是按账户编号分组
我是这样写的:
Map<Account, Long> totalSumOfTransByEachAccount =
transactions.stream()
.collect(Collectors.groupingBy(Transaction::getAccount, Collectors.reducing(0, Transaction::getSum, Long::sum)));
但我需要带有字符串键的映射 - Account.getNumber()
Map<String, Long> totalSumOfTransByEachAccount =
transactions.stream()
.collect(Collectors. ??????)
谁能帮帮我?
最佳答案
还有一个变体,我的决定:
Collectors.groupingBy(t -> t.getAccount().getNumber(),
Collectors.reducing(0L, Transaction::getSum, Long::sum))
关于java - 使用 Java Stream API 按字段分组计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48775578/