如何创建Multimap< K,V>来自地图< K,Collection< V>>? [英] How to create a Multimap<K,V> from a Map<K, Collection<V>>?
本文介绍了如何创建Multimap< K,V>来自地图< K,Collection< V>>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有找到这样的多图构造...当我想要这样做时,我遍历地图,并填充多图。还有其他方法吗?
I didn't find such a multimap construction... When I want to do this, I iterate over the map, and populate the multimap. Is there an other way?
final Map<String, Collection<String>> map = ImmutableMap.<String, Collection<String>>of(
"1", Arrays.asList("a", "b", "c", "c"));
System.out.println(Multimaps.forMap(map));
final Multimap<String, String> expected = ArrayListMultimap.create();
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
expected.putAll(entry.getKey(), entry.getValue());
}
System.out.println(expected);
第一个结果是 {1 = [[a,b,c, c]]}
但我希望 {1 = [a,b,c,c]}
The first result is {1=[[a, b, c, c]]}
but I expect {1=[a, b, c, c]}
推荐答案
假设你有
Map<String, Collection<String>> map = ...;
Multimap<String, String> multimap = ArrayListMultimap.create();
然后我相信这是你能做的最好的
Then I believe this is the best you can do
for (String key : map.keySet()) {
multimap.putAll(key, map.get(key));
}
或更优,但更难阅读
for (Entry<String, Collection<String>> entry : map.entrySet()) {
multimap.putAll(entry.getKey(), entry.getValue());
}
这篇关于如何创建Multimap< K,V>来自地图< K,Collection< V>>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文