繁体   English   中英

如何使用Guava将MultiMap <Integer,Foo>转换为Map <Integer,Set <Foo >>?

[英]How can I convert MultiMap<Integer, Foo> to Map<Integer, Set<Foo>> using Guava?

我正在使用Google Guava 12中的MultiMap,如下所示:

Multimap<Integer, OccupancyType> pkgPOP = HashMultimap.create();

将值插入此multimap后,我需要返回:

Map<Integer, Set<OccupancyType>>

但是,当我这样做时:

return pkgPOP.asMap();

它归还给我

Map<Integer, Collection<OccupancyType>>

如何返回Map<Integer, Set<OccupancyType>>

看看这个问题并由 Guava dev负责人Kevin 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();

编辑:

从Guava 15.0开始,您可以使用帮助方法以更优雅的方式执行此操作:

Map<Integer, Set<OccupancyType>> mapOfSets = Multimaps.asMap(pkgPOP);

番石榴贡献者:

做不安全的演员。 这样会很安全。

由于Java继承的工作方式Map<K, Set<V>>它无法返回Map<K, Set<V>> 基本上, Multimap超类型必须返回Map<K, Collection<V>> ,并且因为Map<K, Set<V>>不是Map<K, Collection<V>>的子类型,所以你不能覆盖asMap()以返回Map<K, Set<V>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM