如何使用流做Map of Maps的深度拷贝?



最简单的方法是遍历,但那样会很冗长,我更喜欢Java 8中更简洁的解决方案。

这篇文章推荐

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

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

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

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

最新更新