Skip to content
Advertisement

Grouping list of object by a field & applying binary function in one of the field to reduce it by sum in one line of code using stream java 8

Let’s take for an example I have list of transaction which contains txnId, paymentCode, amount. Output should be each payment code wise how much amount collected.

I tried to group it based on payment code as key, & list of amount for the payment code, but I am not able to reduce it.

JavaScript

Which gives the output of

JavaScript

But, expectation is

JavaScript

Advertisement

Answer

JavaScript

(with exactly your expected output)

enter image description here

Really, summingInt is a Collector where groupingBy will put every group, you can “sum ints” or whatever you want.

For example, if the group data is not directly integers, you can map:

JavaScript

readed as “with payments as stream, grouping by payment code, take the product of the amount and the txnId and give me the sum total”.

But, of course, exists millions of combinations, instead simply sum you could summarize (min, max, avg, …) and do something with this:

JavaScript

readed as “with payments as stream, grouping by payment code, summarize the product of the amount and the txnId and then give me the average”.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement