我使用Multimap之从谷歌番石榴12所示:
Multimap<Integer, OccupancyType> pkgPOP = HashMultimap.create();
值插入此多重映射后,我需要返回:
Map<Integer, Set<OccupancyType>>
然而,当我这样做:
return pkgPOP.asMap();
它返回我
Map<Integer, Collection<OccupancyType>>
我怎样才能返回Map<Integer, Set<OccupancyType>>
呢?
看看这个问题,并凯文Bourrillion评论#2 ,头番石榴开发:
您可以双击投的Map<K, Collection<V>>
第一到原始地图,然后在Map<K, Set<V>>
你想要的。 你必须抑制未检查的警告,你应该在这一点上发表评论,“安全的,因为SetMultimap保证这一点。” 我甚至可以更新SetMultimap的javadoc提到这一招。
所以,做选中主演:
@SuppressWarnings("unchecked") // Safe because SetMultimap guarantees this.
final Map<Integer, Set<OccupancyType>> mapOfSets =
(Map<Integer, Set<OccupancyType>>) (Map<?, ?>) pkgPOP.asMap();
编辑:
由于番石榴15.0您可以使用helper方法来做到这一点更优雅的方式:
Map<Integer, Set<OccupancyType>> mapOfSets = Multimaps.asMap(pkgPOP);
番石榴贡献者这里:
做不安全的演员。 这将是安全的。
它不能返回Map<K, Set<V>>
由于的方式Java继承工作。 本质上, Multimap
父不得不返回Map<K, Collection<V>>
,因为Map<K, Set<V>>
是不是一个亚型Map<K, Collection<V>>
,你不能覆盖asMap()
返回一个Map<K, Set<V>>
。