流API汇总并收集到Map中

Dex*_*ter 3 java java-8 java-stream

假设你有这样的物体地图(虽然想象它更大):

List<Map<String, Object>>

[{
    "rtype": "133",
    "total": 2555
}, {
    "rtype": "133",
    "total": 5553
}, {
    "rtype": "135",
    "total": 100
}]
Run Code Online (Sandbox Code Playgroud)

rtype = 133,其中有两个!

我想用Streams做的是:

//result:
//Map<String, Object(or double)>
{"133": 2555+5553, "135": 100} // SUM() of the 133s
Run Code Online (Sandbox Code Playgroud)

我在理解Collectors&groupBy的工作方式时遇到了一些麻烦,但我想这可能会用于这种情况.

在Java流API中对此进行编码的正确方法是什么?

我在使用地图找到类似的例子时遇到了麻烦(人们在他们的例子中使用了更多的列表)

shm*_*sel 9

首先,你真的应该使用适当的类而不是地图.话虽如此,您可以按照以下方式对地图列表进行分组:

Map<String, Double> grouped = maps.stream()
        .collect(Collectors.groupingBy(m -> (String)m.get("rtype"),
                Collectors.summingDouble(m -> ((Number)m.get("total")).doubleValue())));
Run Code Online (Sandbox Code Playgroud)