I really like the Multimap 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 Multimaps.index() function which takes an Iterable and a key function and returns a Multimap which groups (or indexes or maps) the elements of the Iterable by the value the function returns for each of those elements.
What I find a bit strange is that Multimap.values() 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 Multimap.asMap() and then call values() on that.
Does anyone know why it may make sense that Multimap behaves that way?
Multimap.asMap().values()isn’t a way around the problem — it was deliberate thatMultimapprovides both ways of accessing it, getting aCollection<Collection<V>>viaasMap().values()and getting the flattenedCollection<V>withvalues().More generally speaking,
Multimaptries not to just be “a map to collections,” but rather “a general way to associate keys with multiple values.” So you get theentries()method in addition tovalues()andkeys(). TheasMap()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
valuesmethod is just meant to fill a different niche than the one filled byasMap().values().