Fab Fab - 2 months ago 13
Java Question

Reducing Map by using Java 8 Stream API

I have a Map in the following form:

Map<Integer, Map<String,Double>> START


Let INNER be the inner map, i.e.

Map<String,Double>


For example, I'd like to reduce START map in a new one

Map<Integer, Double> END


which have the same keys, but different values.
In particular, for each key, I want the new Double value be the SUM of values in the INNER map for the corresponding key.

How could I achieve this by using JAVA 8's STREAM API?

Thanks everyone.

EDIT: A sample map is

------------------------------
| | 2016-10-02 3.45 |
| ID1 | 2016-10-03 1.23 |
| | 2016-10-04 0.98 |
------------------------------
| | 2016-10-02 1.00 |
| ID2 | 2016-10-03 2.00 |
| | 2016-10-04 3.00 |
------------------------------


e I'd like a new map like the following one:

--------------------------------
| | |
| ID1 | SUM(3.45,1.23,0.98) |
| | |
--------------------------------
| | |
| ID2 | SUM(1.00,2.00,3.00) |
| | |
--------------------------------

Answer

It will work for you

    Map<Integer, Double> collect = START.keySet()
                .stream()
                .collect(
                     Collectors.toMap(k -> k, k -> START.get(k)
                         .values()
                         .stream()
                         .reduce(0d, (a, b) -> a + b))
                );