gpt4 book ai didi

java - 使用 Java Stream API 按字段分组计算总和

转载 作者:搜寻专家 更新时间:2023-11-01 02:00:38 25 4
gpt4 key购买 nike

你有两个类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com