nansen nansen - 1 year ago 184
Java Question

Why does guava Multimap.values() return a flat collection instead of a collection of collections?

I really like the

class of the google guava library. It is a map type where you can add multiple values for a key, so it effectively maps from a key to a collection of some type. What I especially love is the
function which takes an
and a key function and returns a
which groups (or indexes or maps) the elements of the
by the value the function returns for each of those elements.

What I find a bit strange is that
returns a flat collection instead of a collection of collections? So the grouping the index function gave me is lost once Ì retrieve the values. I can circumvent that problem by calling
and then call values() on that.

Does anyone know why it may make sense that
behaves that way?

Answer Source

Multimap.asMap().values() isn't a way around the problem -- it was deliberate that Multimap provides both ways of accessing it, getting a Collection<Collection<V>> via asMap().values() and getting the flattened Collection<V> with values().

More generally speaking, Multimap tries not to just be "a map to collections," but rather "a general way to associate keys with multiple values." So you get the entries() method in addition to values() and keys(). The asMap() view provides a way to treat it as a "map to collections," but that has very different semantics that aren't always what you're looking for.

In any event, the values method is just meant to fill a different niche than the one filled by asMap().values().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download