Reduce map using java 8 stream API

I have a map of the following table:

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

Make inner an internal map, i.e

Map<String,Double>

For example, I want to reduce the start map in the new map

Map<Integer,Double> END

It has the same key but different values In particular, for each key, I want the new double value to be sum of the value of the corresponding key in the inner map

How can I achieve this by using java 8's stream API?

Thank you

Edit: 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   |
------------------------------

I want a new map like the following:

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

Solution

It will be useful to you

Map<Integer,Double> collect = START.entrySet()
        .stream()
        .collect(
            Collectors.toMap(
                Map.Entry::getKey,e -> e.getValue()
                      .values()
                      .stream()
                      .reduce(0d,(a,b) -> a + b)
                )
        );
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>