使用Java 8 Streams的收集器根据现有键/值对增加值 [英] Using Java 8 Streams' Collectors to increment value based of existing key/value pair
问题描述
假设有一个List<Object>
,并且Object
包含两种方法:getUserId
和getPoints
.
Suppose there is a List<Object>
and that Object
contains two methods: getUserId
and getPoints
.
考虑List<Object>
包含三个对象,并且它们包含以下数据:
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
正确收集了此内容后,我希望它具有一个如下所示的Map<String, Integer>
:
After collecting this properly, I am expecting to have a Map<String, Integer>
that would look like this:
A: 8,
B: 1
我正在尝试使用Java的8个功能接口(流)进行此操作,因为我只需要最终结果,而在它们之间也不需要任何映射.如果没有其他方法,我愿意对此进行修改. 我首先想到了这个:
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
如何调整Collectors.toMap()
中的最后一位以根据已存储在映射中的值自动增加其值,以便产生上面的结果?
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?
推荐答案
使用 Collectors.summingInt
作为下游收集器:
Use Collectors.groupingBy
together with Collectors.summingInt
as a downstream collector:
this.service.getListObject()
.stream().collect(Collectors.groupingBy(
Object::getUserId, Collectors.summingInt(Object::getPoints)));
这篇关于使用Java 8 Streams的收集器根据现有键/值对增加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!