使用流映射Java中的值



我有一个映射Map<String, Map<String, String>> myMap = new HashMap<>();,我想重新映射它以获得它的值,这样我就得到了Map<String, String>

是否可以使用流API进行映射?

我已经使用for循环解决了这个问题,但我很感兴趣的是,是否可以使用流来完成。

我的解决方案:

Map<String, String> result = new HashMap<>();
myMap.forEach((k, v) -> {
result.putAll(v);
});

我想要的是从myMap中获取所有值,并将它们放在一个新的Map中。

如果确定没有重复的键,可以这样做。

Map<String, String> res = myMap.values()
.stream()
.flatMap(value -> value.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);

如果内部映射之间可能存在重复键,则必须引入合并功能来解决冲突。保持第二个遇到的条目的值的简单解决方案可能如下所示:

Map<String, String> res = myMap.values()
.stream()
.flatMap(value -> value.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v2));

基本上,对Maps的值进行流式处理,将它们展平为条目流,并在新的Map中收集条目。

您需要压平嵌套映射的条目,这可以使用flatMap()mapMulty()来完成。

然后应用collect(),并将收集器toMap()的两个参数风格作为参数传递。这将是足够的,因为你不期望重复。

以下是使用flatMap():的示例

Map<String, Map<String, String>> myMap = new HashMap<>();

Map<String, String> res = myMap.entrySet().stream()         // stream of maps
.flatMap(entry -> entry.getValue().entrySet().stream()) // stream of map entries
.collect(Collectors.toMap(
Map.Entry::getKey,  // key mapper
Map.Entry::getValue // value mapper
));

Java 16mapMulti()用于扁平化数据的示例:

Map<String, Map<String, String>> myMap = new HashMap<>();

Map<String, String> res = myMap.entrySet().stream()   // stream of maps
.<Map.Entry<String, String>>mapMulti((entry, consumer) -> 
entry.getValue().entrySet().forEach(consumer) // stream of map entries
)
.collect(Collectors.toMap(
Map.Entry::getKey,  // key mapper
Map.Entry::getValue // value mapper
));

最新更新