Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream API sum & collect into a Map

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)

like image 594
Dexter Avatar asked Jan 05 '23 09:01

Dexter


1 Answers

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())));
like image 124
shmosel Avatar answered Jan 14 '23 06:01

shmosel