Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

guava: Best way to iterate over the key->collection entries of a Multimap?

I'm looking for the corresponding way, for Multimap, to iterate over entries of a Map, namely:

Map<K,V> map = ...;
for (Map.Entry<K,V> entry : map.entrySet())
{
    K k = entry.getKey();
    V v = entry.getValue();
}

Which of the following is better? (or perhaps more importantly, what are the differences?)

Multimap<K,V> mmap = ...;
for (Map.Entry<K,Collection<V>> entry : mmap.asMap().entrySet())
{
    K k = entry.getKey();
    Collection<V> v = entry.getValue();
}

or

Multimap<K,V> mmap = ...;
for (K k : mmap.keySet())
{
    Collection<V> v = mmap.get(k);
}
like image 837
Jason S Avatar asked Jul 12 '11 17:07

Jason S


People also ask

What is multimap in guava?

Introduction : A Multimap is a general way to associate keys with arbitrarily many values. Guava’s Multimap framework makes it easy to handle a mapping from keys to multiple values. There are two ways to think of a Multimap conceptually : 1) As a collection of mappings from single keys to single values.

How to iterate over keys or values in map in Java?

Iterating over keys or values using keySet () and values () methods Map.keySet () method returns a Set view of the keys contained in this map and Map.values () method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops.

How to iterate over a collection in Java?

Different ways to iterate over Collections in Java 1 Iterable.forEach method (Java 8) 2 Java “foreach” loop (Java 5) 3 java.util.Iterator (Java 2) 4 Traditional for loop

When is a key contained in the multimap?

A key is contained in the Multimap if and only if it maps to at least one value. Any operation that causes a key to has zero associated values, has the effect of removing that key from the Multimap.


1 Answers

They're both valid; the second tends to be a lot easier to read (especially as you can get an actual List out of a ListMultimap and so on), but the first might be more efficient (to a degree that may or may not matter to you).

like image 91
Kevin Bourrillion Avatar answered Sep 20 '22 22:09

Kevin Bourrillion