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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With