broconne broconne - 4 months ago 47
Java Question

Filtering Guava Multimaps

Is there a a built-in method or combination of methods to return a filtered view of Guava ImmutableMultimaps using predicates, like you can with regular maps?

There does not appear to be Maps.filter method that accepts an ImmutableMultimap as a parameter. Looking at the API I could call asMap() and get a map based view of the multimap and perform the filter that way. However, I need to return an ImmutableMultimap from my function and for obvious reasons there isn't a way to view a Map> as an ImmutableMultimap - without having to contruct a new Multimap.

Even if I could filter it as a Map and cast it back to an ImmutableMultimap since they are all just views (I think?), the filter methods would only let me filter on the collection as a whole not removing individual values.


Upon reflection, I don't think there is a way to create a filtered view of an ImmutableMultimap for a very good reason. If an object expects an ImmutableMultiMap, it would expect that object to not appear to change for the lifetime of the object. Applying a filter, that could operate dynamically, would break that implied (or possible written for all I know) contract as it would appear that between calls to various methods the map had in fact mutated.