Java 如何从 Map<K, Collection<V>> 创建 Multimap<K,V>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3093863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:25:00  来源:igfitidea点击:

How to create a Multimap<K,V> from a Map<K, Collection<V>>?

javaguavamultimap

提问by sly7_7

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);

The first result is {1=[[a, b, c, c]]}but I expect {1=[a, b, c, c]}

第一个结果是{1=[[a, b, c, c]]}但我期望{1=[a, b, c, c]}

采纳答案by Kevin Bourrillion

Assuming you have

假设你有

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));
}

or the more optimal, but harder to read

或者更优,但更难阅读

for (Entry<String, Collection<String>> entry : map.entrySet()) {
  multimap.putAll(entry.getKey(), entry.getValue());
}

回答by Hank Gay

UPDATE: For what you're asking, I think you're going to need to fall back to Multimap.putAll.

更新:对于您的要求,我认为您将需要回退到Multimap.putAll.

回答by Daniel Alexiuc

Here is a useful generic version that I wrote for my StuffGuavaIsMissingclass.

这是我为我的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;
}

And an immutable version:

还有一个不可变的版本:

/**
 * 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();
}

回答by Somnath Kadam

Following code without Google's Guava library. It is used for double value as key and sorted order

以下代码没有谷歌的番石榴库。它用于双值作为键和排序顺序

Map<Double,List<Object>> multiMap = new TreeMap<Double,List<Object>>();

for( int i= 0;i<15;i++)
{
    List<Object> myClassList = multiMap.get((double)i);
    if(myClassList == null)
    {
        myClassList = new ArrayList<Object>();
        multiMap.put((double) i,myClassList);
    }
    myClassList.add("Value "+ i);
}

List<Object> myClassList = multiMap.get((double)0);
if(myClassList == null)
{
    myClassList = new ArrayList<Object>();
    multiMap.put( (double) 0,myClassList);
}
myClassList.add("Value Duplicate");
for (Map.Entry entry : multiMap.entrySet()) 
{
  System.out.println("Key = " + entry.getKey() + ", Value = " +entry.getValue());
}

回答by Dillon Ryan Redding

This question is a little old, but I thought I'd give an updated answer. With Java 8 you could do something along the lines of

这个问题有点老了,但我想我会给出一个更新的答案。使用 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);

This should give you {1=[a, b, c, c]}, as desired.

这应该给你{1=[a, b, c, c]},如你所愿。

回答by Héctor Mu?oz Berzosa

LinkedListMultimap<String, String> mm = map.entrySet()
    .stream()
    .collect(
        () -> LinkedListMultimap.create(map.size()),
        (m, e) -> m.putAll(e.getKey(), e.getValue()),
        (m1, m2) -> m1.putAll(m2));