sly*_*7_7 43 java multimap guava
我没有找到这样的多图构造...当我想要这样做时,我遍历地图,并填充多图.还有其他方法吗?
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);
Run Code Online (Sandbox Code Playgroud)
第一个结果是,{1=[[a, b, c, c]]}但我期待{1=[a, b, c, c]}
Kev*_*ion 47
假设你有
Map<String, Collection<String>> map = ...;
Multimap<String, String> multimap = ArrayListMultimap.create();
Run Code Online (Sandbox Code Playgroud)
然后我相信这是你能做的最好的事情
for (String key : map.keySet()) {
multimap.putAll(key, map.get(key));
}
Run Code Online (Sandbox Code Playgroud)
或者更优化,但更难阅读
for (Entry<String, Collection<String>> entry : map.entrySet()) {
multimap.putAll(entry.getKey(), entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
这是我为StuffGuavaIsMissing类编写的有用的通用版本.
/**
* Creates a Guava multimap using the input map.
*/
public static <K, V> Multimap<K, V> createMultiMap(Map<K, ? extends Iterable<V>> input) {
Multimap<K, V> multimap = ArrayListMultimap.create();
for (Map.Entry<K, ? extends Iterable<V>> entry : input.entrySet()) {
multimap.putAll(entry.getKey(), entry.getValue());
}
return multimap;
}
Run Code Online (Sandbox Code Playgroud)
一个不可变的版本:
/**
* Creates an Immutable Guava multimap using the input map.
*/
public static <K, V> ImmutableMultimap<K, V> createImmutableMultiMap(Map<K, ? extends Iterable<V>> input) {
ImmutableMultimap.Builder<K, V> builder = ImmutableMultimap.builder();
for (Map.Entry<K, ? extends Iterable<V>> entry : input.entrySet()) {
builder.putAll(entry.getKey(), entry.getValue());
}
return builder.build();
}
Run Code Online (Sandbox Code Playgroud)
这个问题有点旧,但我想我会给出一个更新的答案.使用Java 8,你可以做一些事情
ListMultimap<String, String> multimap = ArrayListMultimap.create();
Map<String, Collection<String>> map = ImmutableMap.of(
"1", Arrays.asList("a", "b", "c", "c"));
map.forEach(multimap::putAll);
System.out.println(multimap);
Run Code Online (Sandbox Code Playgroud)
{1=[a, b, c, c]}根据需要,这应该给你.