【问题标题】:How to do a deep copy of a Map of Maps using streams?如何使用流对地图进行深度复制?
【发布时间】:2021-08-09 17:26:32
【问题描述】:

最简单的方法是循环,但这会很冗长,我更喜欢 Java 8 的更简洁的解决方案。

This post over here推荐

mapCopy = map.entrySet().stream()
    .collect(Collectors.toMap(e -> e.getKey(), e -> List.copyOf(e.getValue())))

用于复制HashMap<Integer, List>,但我拥有的是HashMap<String, HashMap<String, Integer>。我也为列表尝试了上述方法,但由于某种原因,e.getKey()e.getValue() 都“无法解决”,即使 IntelliJ 自动将其预测为有效方法,e 指的是 Map.Entry

我不太擅长使用流,所以我不知道为什么上面的方法不起作用,或者如何完成我想要的。

【问题讨论】:

  • 该值是否可以包含其他地图?值是什么类型的 Map?
  • 已编辑! HashMap>

标签: java java-stream


【解决方案1】:

您可以使用HashMap 构造函数创建原始Map 中每个值的(浅)副本。

Map<String, Map<String, Integer>> result = map.entrySet().stream()
   .collect(Collectors.toMap(Map.Entry::getKey, e -> new HashMap<>(e.getValue())));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-01
    • 2018-10-08
    • 2019-10-22
    • 2011-09-25
    • 2014-09-05
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    相关资源
    最近更新 更多