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

Jason S picture Jason S · Jul 12, 2011 · Viewed 8.6k times · Source

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

Answer

Kevin Bourrillion picture Kevin Bourrillion · Jul 14, 2011

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