繁体   English   中英

如何转换地图 <String, List<String> &gt;到地图 <String, String> 在Java 8功能性API中

[英]How to Convert a Map<String, List<String>> to Map<String, String> in java 8 functional APIs

我有一张下面的地图,

 [key = "car", value = ["bmw", "toyota"]]
 [key = "bike", value = ["honda", "kawasaki"]]

我想使用以下Java 8功能性API将其转换为另一张地图,

 [key = "bmw", value = "car"]
 [key = "toyota", value = "car"]
 [key = "honda", value = "bike"]
 [key = "kawasaki", value = "bike"]

将地图值展平为条目,然后收集它们:

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));

可以通过导入AbstractMap.SimpleEntryMap.Entry来缩短此时间。

不需要构造临时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);

您可能会注意到与非流解决方案的相似之处

Map<String, String> result = new HashMap<>();
source.forEach((key, value) -> value.forEach(k -> result.put(k, key)));

或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.

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