使用Java 8 Stream API减少地图 [英] Reducing Map by using Java 8 Stream API

查看:126
本文介绍了使用Java 8 Stream API减少地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的地图:

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

让INNER作为内部地图,即

Let INNER be the inner map, i.e.

Map<String,Double>

例如,我想在一个新地图中缩小START地图

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

Map<Integer, Double> END

具有相同的键,但值不同. 特别是,对于每个键,我希望新的Double值是INNER映射中对应键的值的总和.

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.

如何使用JAVA 8的STREAM API实现此目标?

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

谢谢大家.

示例地图为

------------------------------
|      |  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我想要一张新的地图,如下图:

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)  |
|      |                       |
--------------------------------

推荐答案

它将为您服务

    Map<Integer, Double> collect = START.entrySet()
        .stream()
        .collect(
            Collectors.toMap(
                Map.Entry::getKey, 
                e -> e.getValue()
                      .values()
                      .stream()
                      .reduce(0d, (a, b) -> a + b)
                )
        );

这篇关于使用Java 8 Stream API减少地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆