Java 8 convert Maplt;K, Listlt;Vgt;gt; to Maplt;V, Listlt;Kgt;gt;(Java 8 转换 Maplt;K, Listlt;Vgt;gt;到地图lt;V,列表lt;Kgt;gt;)
问题描述
我需要将 Map
转换为 Map
I need to convert Map<K, List<V>>
to Map<V, List<K>>
.
I've been struggling with this issue for some time.
Map
Map
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, toList())
)
但我找不到解决初始问题的方法.有一些易于准备的 java-8 方法吗?
But I can't find solve an initial issue. Is there some easy-to-ready-java-8 way to do it?
推荐答案
我认为你很接近,你需要将这些条目 flatMap
到 Stream
并从那里.我使用了已经存在的 SimpleEntry
,但你也可以使用某种 Pair
.
I think you were close, you would need to flatMap
those entries to a Stream
and collect from there. I've used the already present SimpleEntry
, but you can use a Pair
of some kind too.
initialMap.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream().map(v -> new SimpleEntry<>(entry.getKey(), v)))
.collect(Collectors.groupingBy(
Entry::getValue,
Collectors.mapping(Entry::getKey, Collectors.toList())
));
好吧,如果您不想为那些 SimpleEntry
实例增加额外的开销,您可以做一些不同的事情:
Well, if you don't want to create the extra overhead of those SimpleEntry
instances, you could do it a bit different:
Map<Integer, List<String>> result = new HashMap<>();
initialMap.forEach((key, values) -> {
values.forEach(value -> result.computeIfAbsent(value, x -> new ArrayList<>()).add(key));
});
这篇关于Java 8 转换 Map<K, List<V>>到地图<V,列表<K>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 转换 Map<K, List<V>>到地图<V,列表<K>>


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01