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


基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13