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, there's two of them!
What I want to do with Streams is this:
//result:
//Map<String, Object(or double)>
{"133": 2555+5553, "135": 100} // SUM() of the 133s
I have a bit of trouble understanding how Collectors & groupBy stuff works but I imagine that might be used for this case.
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())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With