El uso de colectores de Java 8 Streams' a valor de incremento con base de / valor par de claves existente

Gustavo Silva :

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?

Oleksandr Pyrohov :

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

this.service.getListObject()
    .stream().collect(Collectors.groupingBy(
        Object::getUserId, Collectors.summingInt(Object::getPoints)));

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=226442&siteId=1
Recomendado
Clasificación