问题描述
假设您有一个这样的对象图(尽管可以想象它更大):
Say you have a map of objects like this (though imagine it being bigger):
List< Map< String,Object>>
[{
"rtype": "133",
"total": 2555
}, {
"rtype": "133",
"total": 5553
}, {
"rtype": "135",
"total": 100
}]
rtype = 133,有两个!
rtype=133, there's two of them!
我要对Streams进行以下操作:
What I want to do with Streams is this:
//result:
//Map<String, Object(or double)>
{"133": 2555+5553, "135": 100} // SUM() of the 133s
我很难理解Collectors&groupBy的东西可以工作,但我想这可能用于这种情况.
I have a bit of trouble understanding how Collectors & groupBy stuff works but I imagine that might be used for this case.
在Java Streams API中对此进行编码的正确方法是什么?
What's the proper way to code this in Java streams API?
我在查找相似的地图示例时遇到了麻烦(人们在示例中使用列表的次数更多)
I'm having trouble finding similar examples with maps (people use lists a lot more in their examples)
推荐答案
首先,您确实应该使用适当的类而不是地图.话虽如此,这是将地图列表分组的方法:
First of all, you really should be using proper classes instead of maps. Having said that, here's how you can group your list of maps:
Map<String, Double> grouped = maps.stream()
.collect(Collectors.groupingBy(m -> (String)m.get("rtype"),
Collectors.summingDouble(m -> ((Number)m.get("total")).doubleValue())));
这篇关于流API总和收集到地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!