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);
}
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.
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.
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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With