首页 > 解决方案 > AttributeValue java流上的summingDouble

问题描述

我有一个 String、AttributeValue 的 Map 列表,并想使用summingDouble它来对键进行分组并分别找到每个键的总和。

例如,

    List<Map<String, AttributeValue>> ls = new ArrayList<Map<String, AttributeValue>>();

    Map<String,AttributeValue> map = new HashMap<String,AttributeValue>();
    map.put("key1", new AttributeValue().withN("1000"));
    map.put("key2", new AttributeValue().withN("1000"));


    ls.add(map);
    Map<String,AttributeValue> map1 = new HashMap<String,AttributeValue>();
    map1.put("key3", new AttributeValue().withN("1000"));
    map1.put("key1", new AttributeValue().withN("2000"));
    ls.add(map1);

这应该返回

result = {key1: 3000, key2: 1000, key3: 1000}

其中 key1 是 key1 的值的总和。

尝试如下,但在这种情况下 getValue 是一个 AttributeValue 所以它不起作用。

Map<String, Double> result = ls.stream().flatMap(m -> m.entrySet().stream()).collect(groupingBy(Map.Entry::getKey, summingDouble(Map.Entry::getValue)));

标签: lambdajava-8java-streamreduceentity-attribute-value

解决方案


看来您的 groupingBy 应该是这样的:

groupingBy(
    Map.Entry::getKey, 
    summingDouble(e -> Double.valueOf(e.getValue().getN())))

推荐阅读