Skip to content
Advertisement

Java Stream GroupBy and Reduce

I have an Item class which contains a code, quantity and amount fields, and a list of items which may contain many items (with same code). I want to group the items by code and sum up their quantities and amounts.

I was able to achieve half of it using stream’s groupingBy and reduce. The grouping by worked, but the reduce is reducing all of the grouped items into one single item repeated over the different codes (groupingBy key).

Shouldn’t reduce here reduce the list of items for each code from the map? Why is it retuning the same combined item for all.

Below is a sample code.

JavaScript

and below is the output.

JavaScript

Advertisement

Answer

You must not modify the input arguments to Collectors.reducing. new Item() is only executed once and all your reduction operations will share the same “aggregation instance”. In other words: the map will contain the same value instance 4 times (you can easily check yourself with System.identityHashCode() or by comparing for reference-equality: aggregatedItems.get("CODE1") == aggregatedItems.get("CODE2")).

Instead, return a new result instance:

JavaScript

Output:

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