Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java 8 Streams' Collectors to increment value based of existing key/value pair

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?

like image 395
Gustavo Silva Avatar asked Jun 14 '19 16:06

Gustavo Silva


1 Answers

Use Collectors.groupingBy together with Collectors.summingInt as a downstream collector:

this.service.getListObject()
    .stream().collect(Collectors.groupingBy(
        Object::getUserId, Collectors.summingInt(Object::getPoints)));
like image 64
Oleksandr Pyrohov Avatar answered Nov 10 '22 09:11

Oleksandr Pyrohov