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的转换很明显:
但我找不到解决初始问题的方法.有一些易于准备的 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.
好吧,如果您不想为那些 SimpleEntry
实例增加额外的开销,您可以做一些不同的事情:
Well, if you don't want to create the extra overhead of those SimpleEntry
instances, you could do it a bit different:
这篇关于Java 8 转换 Map<K, List<V>>到地图<V,列表<K>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!