我需要转换Map<K, List<V>>
to Map<V, List<K>>
。
我已经为这个问题苦苦挣扎了一段时间。
如何进行转换很明显Map<K, V>
to Map<V, List<K>>
:
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, toList())
)
但我找不到解决初始问题的方法。有没有一些易于使用的 java-8 方法来做到这一点?
我想你已经很接近了,你需要flatMap
这些条目到Stream
并从那里收集。我已经使用了已经存在的SimpleEntry
,但你可以使用Pair
也有某种类型的。
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
实例,你可以做一些不同的事情:
Map<Integer, List<String>> result = new HashMap<>();
initialMap.forEach((key, values) -> {
values.forEach(value -> result.computeIfAbsent(value, x -> new ArrayList<>()).add(key));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)