繁体   English   中英

如何使用Java 8流式api从地图列表创建地图地图

[英]How to create a map of maps from a list of maps with Java 8 streaming api

背景

我有一个看起来像这样的地图列表:

[
  {
    "name": "A",
    "old": 0.25,
    "new": 0.3
  },
  {
    "name": "B",
    "old": 0.3,
    "new": 0.35
  },
  {
    "name": "A",
    "old": 0.75,
    "new": 0.7
  },
  {
    "name": "B",
    "old": 0.7,
    "new": 0.60
  }
]

我希望输出看起来像这样:

{
  "A": {
    "old": 1,
    "new": 1
  },
  "B": {
    "old": 1,
    "new": 0.95
  }
}

...将每个相关条目的old值和new值相加。

映射List<Map<String, Object>>的数据类型是List<Map<String, Object>> ,因此输出应该是Map<String, Map<String, Double>>

我试过的

通过一些图表绘图,文档阅读和反复试验,我能够想出这个:

data.stream()
    .collect(
        Collectors.groupingBy(entry -> entry.get("name"),
            Collectors.summingDouble(entry ->
                Double.parseDouble(entry.get("old").toString())))
    );

生成一个Map<String, Double>类型的对象,其中输出为

{
  "A": 1,
  "B": 1
}

对于old值的总结。 但是,我无法将其转换为地图地图。 像这样的东西:

data.stream()
    .collect(
        Collectors.groupingBy(entry -> entry.get("name"),
            Collectors.mapping(
                Collectors.groupingBy(entry -> entry.get("old"),
                    Collectors.summingDouble(entry ->
                        Double.parseDouble(entry.get("old").toString())
                    )
                ),
                Collectors.groupingBy(entry -> entry.get("new"),
                    Collectors.summingDouble(entry ->
                        Double.parseDouble(entry.get("new").toString())
                    )
                )
            )
        )
    );

不起作用,因为Collectors.mapping()只接受一个映射函数和一个下游收集器,但我不确定如何一次映射两个值。

我需要另一个函数来创建两个不同值的映射吗? 关于更好的方法的任何建议也非常感谢。

您可以使用流,但您也可以使用MapcomputeIfAbsentmerge方法:

Map<String, Map<String, Double>> result = new LinkedHashMap<>();
data.forEach(entry -> {
    String name = (String) entry.get("name");
    Map<String, Double> map = result.computeIfAbsent(name, k -> new HashMap<>());
    map.merge("old", (Double) entry.get("old"), Double::sum);
    map.merge("new", (Double) entry.get("new"), Double::sum);
});

仅使用Stream工具(类似于 )可以实现此目的

Map<String, Map<String, Double>> collect = data.stream().collect(
    Collectors.groupingBy(m -> (String)m.get("name"),
    Collector.of(LinkedHashMap::new,
        (acc, e) -> Stream.of("old", "new").forEach(key -> acc.merge(key, (Double) e.get(key), Double::sum)),
        (m1, m2) -> {
          m2.forEach((k, v) -> m1.merge(k, v, Double::sum));
          return m1;
        })
    ));

还有> Java 8方式:

Map<String, Map<String, Double>> stats = data.stream().collect(
    Collectors.groupingBy(m -> (String) m.get("name"),
        Collectors.flatMapping(m -> m.entrySet().stream().filter(e -> !"name".equals(e.getKey())),
            Collectors.toMap(Map.Entry::getKey, e -> (Double)e.getValue(), Double::sum, LinkedHashMap::new)
        )
    ));

您在第一次尝试时接近解决方案,但是您需要执行一些自定义代码才能完全完成图片。

您将需要实现自己的收集器 ,将多个地图转换为单个双地图。

这看起来像:

       Collector.of(
            () -> new HashMap<>(),
            (Map<String, Double>target, Map<String, Object> source) -> {
                target.merge("old", (Double)source.get("old"), Double::sum);
                target.merge("new", (Double)source.get("new"), Double::sum);
            },
            (Map<String, Double> map1, Map<String, Double> map2) -> {
                map2.forEach((k, v) -> map1.merge(k, v, Double::sum));
                return map1;
            }
        ) 

这与您的初始分组相结合,尝试解决图片:

data.stream()
    .collect(
        Collectors.groupingBy(entry -> entry.get("name"),
            // Insert collector here
        )
    );

在线完整代码示例: http//tpcg.io/pJftrJ

您可以声明一个名为Pair的类

public class Pair {
    private final double oldVal;
    private final double newVal;

    public Pair(double oldVal, double newVal) {
        super();
        this.oldVal = oldVal;
        this.newVal = newVal;
    }

    public double getOldVal() {
        return oldVal;
    }

    public double getNewVal() {
        return newVal;
    }

    @Override
    public String toString() {
        return "{oldVal=" + oldVal + ", newVal=" + newVal + "}";
    }

}

然后这样做,

Map<Object, Pair> result = sourceMaps.stream()
        .collect(Collectors.toMap(m -> m.get("name"),
                m -> new Pair((double) m.get("old"), (double) m.get("new")),
                (p1, p2) -> new Pair(p1.getOldVal() + p2.getOldVal(), p1.getNewVal() + p2.getNewVal())));

这是输出,

{A={oldVal=1.0, newVal=1.0}, B={oldVal=1.0, newVal=0.95}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM