Suppose there is a List<Object>
and that Object
contains two methods: getUserId
and getPoints
.
Consider that List<Object>
contains three objects, and they contain the following data:
userId A; 3 points
userId A; 5 points
userId B; 1 point
After collecting this properly, I am expecting to have a Map<String, Integer>
that would look like this:
A: 8,
B: 1
I am attempting this using Java's 8 functional interfaces, the streams, because I only need the final result and I do not have nor need any of these mappings in between. I am willing to modify this if there is no other way. I first came up with this:
this.service.getListObject()
.stream()
.collect(Collectors.toMap(Object::getUserId, Object::getPoints));
However, this has shown insufficient because it will always replace the key with the newest value, thus producing:
A: 5,
B: 1
How can I tweak the last bits from the Collectors.toMap()
to automatically increment its value according to the value already stored in the map, so that I produce the result above?
Use Collectors.groupingBy
together with Collectors.summingInt
as a downstream collector:
this.service.getListObject()
.stream().collect(Collectors.groupingBy(
Object::getUserId, Collectors.summingInt(Object::getPoints)));
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