开发者

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>开发者_JS百科; mmap = ...;
for (K k : mmap.keySet())
{
    Collection<V> v = mmap.get(k);
}


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


I would say that the Guava folks were considerate enough to allow you to do it either way, depending on your needs. For example, if the structure does is important, and you wish to view your multimap in a grouped manner, the latter would be preferential. OTOH, if you wish to view the multimap as a set of key-value pairs, where duplicate keys are insignificant, you might prefer to use mmap.entries. It's really a matter of what is most appropriate in the context that your multimap is being used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜