Reputation: 303
You have two classes:
Account: number: String, balance: Long
Transaction: uuid: String, sum: Long, account: Account
Both classes have getters for all fields with the corresponding names (getNumber(), getSum(), getAccount() and so on).
I need to calculate sum of transaction for every account, but exactly not by Account, but grouping by Account.number
I make it like this:
Map<Account, Long> totalSumOfTransByEachAccount =
transactions.stream()
.collect(Collectors.groupingBy(Transaction::getAccount, Collectors.reducing(0, Transaction::getSum, Long::sum)));
But I need map with String key - Account.getNumber()
Map<String, Long> totalSumOfTransByEachAccount =
transactions.stream()
.collect(Collectors. ??????)
Can anyone help me?
Upvotes: 4
Views: 1133
Reputation: 56413
You can do so with:
Map<String, Long> resultSet = transactions.stream()
.collect(Collectors.groupingBy(t -> t.getAccount().getNumber(),
Collectors.summingLong(Transaction::getSum)));
Upvotes: 2
Reputation: 303
One more variant, my decision:
Collectors.groupingBy(t -> t.getAccount().getNumber(),
Collectors.reducing(0L, Transaction::getSum, Long::sum))
Upvotes: 4