IvanSPb
IvanSPb

Reputation: 303

Calculate sum using Java Stream API grouping by field

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

Answers (2)

Ousmane D.
Ousmane D.

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

IvanSPb
IvanSPb

Reputation: 303

One more variant, my decision:

 Collectors.groupingBy(t -> t.getAccount().getNumber(),
                    Collectors.reducing(0L, Transaction::getSum, Long::sum))

Upvotes: 4

Related Questions