[英]How to Convert a Map<String, List<String>> to Map<String, String> in java 8 functional APIs
I have a map like bellow, 我有一张下面的地图,
[key = "car", value = ["bmw", "toyota"]]
[key = "bike", value = ["honda", "kawasaki"]]
I want to convert it to another map using java 8 functional apis like bellow, 我想使用以下Java 8功能性API将其转换为另一张地图,
[key = "bmw", value = "car"]
[key = "toyota", value = "car"]
[key = "honda", value = "bike"]
[key = "kawasaki", value = "bike"]
Flatten the map values to entries then collect them: 将地图值展平为条目,然后收集它们:
Map<String, String> m2 = map
.entrySet()
.stream()
.flatMap(e -> e.getValue().stream().map(v -> new AbstractMap.SimpleEntry<>(v, e.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
This can be shortened by importing AbstractMap.SimpleEntry
and Map.Entry
. 可以通过导入
AbstractMap.SimpleEntry
和Map.Entry
来缩短此时间。
A solution that doesn't need constructing temporary Map.Entry
instances, is: 不需要构造临时
Map.Entry
实例的解决方案是:
Map<String, String> result = source.entrySet().stream()
.collect(HashMap::new, (m,e)->e.getValue().forEach(k->m.put(k,e.getKey())), Map::putAll);
You might notice the similarity to the non-stream solution 您可能会注意到与非流解决方案的相似之处
Map<String, String> result = new HashMap<>();
source.forEach((key, value) -> value.forEach(k -> result.put(k, key)));
or the pre-Java 8 solution 或Java 8之前的解决方案
Map<String, String> result = new HashMap<>();
for(Map.Entry<String,List<String>> e: source.entrySet())
for(String key: e.getValue()) result.put(key, e.getKey());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.