4

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?

0

2 Answers 2

4

One more variant, my decision:

 Collectors.groupingBy(t -> t.getAccount().getNumber(),
                    Collectors.reducing(0L, Transaction::getSum, Long::sum))
Sign up to request clarification or add additional context in comments.

1 Comment

The Collectors.reducing factory method is a generalization of pretty much majority of the collectors, however, I'd go with Collectors.summingLong(Transaction::getSum) as suggested in my answer instead of Collectors.reducing(0L, Transaction::getSum, Long::sum) for readability and maybe has better performance as opposed to the long-winded reducing. anyway +1 for coming up with your own answer ;-)
2

You can do so with:

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

2 Comments

Thank you very much ) Maybe it is possible to do it with reduce?
@IvanSPb if the solution has solved your question then please feel free to accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.