I need to convert Map<K, List<V>>
to Map<V, List<K>>
.
I've been struggling with this issue for some time.
It's obvious how to do conversion Map<K, V>
to Map<V, List<K>>
:
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, toList())
)
But I can't find solve an initial issue. Is there some easy-to-ready-java-8 way to do it?
Best Answer
I think you were close, you would need to
flatMap
those entries to aStream
and collect from there. I've used the already presentSimpleEntry
, but you can use aPair
of some kind too.Well, if you don't want to create the extra overhead of those
SimpleEntry
instances, you could do it a bit different: