I'm using MultiMap from Google Guava 12 like this:
Multimap<Integer, OccupancyType> pkgPOP = HashMultimap.create();
after inserting values into this multimap, I need to return:
Map<Integer, Set<OccupancyType>>
However, when I do:
return pkgPOP.asMap();
It returns me
Map<Integer, Collection<OccupancyType>>
How can I return Map<Integer, Set<OccupancyType>>
instead ?
Guava contributor here:
Do the unsafe cast. It'll be safe.
It can't return a
Map<K, Set<V>>
because of the way Java inheritance works. Essentially, theMultimap
supertype has to return aMap<K, Collection<V>>
, and becauseMap<K, Set<V>>
isn't a subtype ofMap<K, Collection<V>>
, you can't overrideasMap()
to return aMap<K, Set<V>>
.Look at this issue and comment #2 by Kevin Bourrillion, head Guava dev:
So do unchecked cast:
EDIT:
Since Guava 15.0 you can use helper method to do this in more elegant way: