Calculate amount 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 (), etc.).

I need to calculate the transaction amount for each account, but definitely not by the Account, but group by Account.number

I do it like this:

Map<Account, Long> totalSumOfTransByEachAccount =
            transactions.stream()
                    .collect(Collectors.groupingBy(Transaction::getAccount, Collectors.reducing(0, Transaction::getSum, Long::sum)));

But I need a card with a string key - Account.getNumber ()

Map<String, Long> totalSumOfTransByEachAccount =
            transactions.stream()
                    .collect(Collectors.  ??????)

Can anybody help me?

+4
source share
2 answers

You can do it with

Map<String, Long> resultSet = transactions.stream()
                .collect(Collectors.groupingBy(t -> t.getAccount().getNumber(),
                               Collectors.summingLong(Transaction::getSum)));
+2
source

Another option, my solution:

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

Source: https://habr.com/ru/post/1693599/


All Articles