Java 8转换Map< Integer,List< String>> to Map< String,List< Integer>>同 [英] Java 8 convert Map<Integer, List<String>> to Map<String, List<Integer>> with
本文介绍了Java 8转换Map< Integer,List< String>> to Map< String,List< Integer>>同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个地图是一个值列表的地图,但我需要反转它,以便
I have a Map is a map to a list of values but I need to inverse it so that
Map<Integer, List<String>>
变为
Map<String, List<Integer>>
例如我有
1 -> { A, B, C }
2 -> { B }
3 -> { A, C }
我希望看到
A -> { 1, 3 }
B -> { 1, 2 }
C -> { 1, 3 }
Java 8中是否有更简单的方法来执行此操作而不是迭代如果映射条目不存在则创建一个集合条目,并添加到列表等?我一直认为这很明显,但我无法解决。
Is there any easier way in Java 8 to do this than having to iterate through the map entries and create a set entry if it does not exist, and add to the list etc? I keep thinking it is really obvious but I cannot work it out.
提前致谢
推荐答案
未经测试,但您可以这样做:
Untested, but you could do something like this:
mapIntToStrings.entrySet().stream()
.flatMap(entryIntToStrings -> entryIntToStrings.getValue().stream()
.map(str -> new AbstractMap.SimpleEntry<>(entryIntToStrings.getKey(), str)))
.collect(groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toList())))
这篇关于Java 8转换Map< Integer,List< String>> to Map< String,List< Integer>>同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文