Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams - how to merge elements from the list with the same fields to one element and sum up

I have one question - I have List of elements A:

class A {
String fieldA;
int fieldB
}

I'd like to merge all elements with thr same fieldA to one element with summed up all values from fieldB this way:

el1 = AAA 5
el2 = AAA 7
el3 = AAA 2

Result:

one element: AAA 14

How can I do this using Java 8 Streams?

So in the end my list has to have less elements than at the beginning. I have to find all elements with the same fieldA and merge them to one element with summed up fieldB.

Thank you!

like image 728
Matley Avatar asked Sep 03 '25 03:09

Matley


1 Answers

You may do it like so,

List<A> reducedAList = aList.stream()
    .collect(Collectors.groupingBy(A::getFieldA, Collectors.summingInt(A::getFieldB)))
    .entrySet().stream()
    .map(e -> new A(e.getKey(), e.getValue()))
    .collect(Collectors.toList());

Rather than replacing the existing List<A> let's create a new list with the reduced A values. For that first create a map considering the value of fieldA as the key and the sum of the fieldB values with the same key as the value. Then iterate over the entrySet of the map and create a new A instance from each entry and collect it into a container. That's what we need.

like image 185
Ravindra Ranwala Avatar answered Sep 07 '25 18:09

Ravindra Ranwala