Cómo crear un Multimap a partir de un mapa?


No encontré tal construcción multimap... Cuando quiero hacer esto, itero sobre el mapa y lleno el multimap. ¿Hay otra manera?

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

El primer resultado es {1=[[a, b, c, c]]}, pero espero {1=[a, b, c, c]}

Author: Alexander Farber, 2010-06-22

6 answers

Asumiendo que tienes

Map<String, Collection<String>> map = ...;
Multimap<String, String> multimap = ArrayListMultimap.create();

Entonces creo que esto es lo mejor que puedes hacer

for (String key : map.keySet()) {
  multimap.putAll(key, map.get(key));
}

O el más óptimo, pero más difícil de leer

for (Entry<String, Collection<String>> entry : map.entrySet()) {
  multimap.putAll(entry.getKey(), entry.getValue());
}
 47
Author: Kevin Bourrillion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-19 06:24:30

Aquí hay una versión genérica útil que escribí para mi clase 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;
}

Y una versión inmutable:

/**
 * 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();
}
 7
Author: Daniel Alexiuc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-04 05:52:46

Esta pregunta es un poco vieja, pero pensé en dar una respuesta actualizada. Con Java 8 usted podría hacer algo en la línea de

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

Esto debería darte {1=[a, b, c, c]}, como desees.

 6
Author: Dillon Ryan Redding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-24 17:24:20

ACTUALIZACIÓN: Para lo que estás pidiendo, creo que vas a necesitar volver a Multimap.putAll.

 2
Author: Hank Gay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-22 14:46:04

Siguiendo el código sin la biblioteca de Guayaba de Google. Se utiliza para el valor doble como clave y orden ordenado

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());
}
 1
Author: Somnath Kadam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-14 15:47:33
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));
 0
Author: Héctor Muñoz Berzosa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-12 07:51:31