java 如何使用 Guava 将 MultiMap<Integer, Foo> 转换为 Map<Integer, Set<Foo>>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11204143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert MultiMap<Integer, Foo> to Map<Integer, Set<Foo>> using Guava?
提问by brainydexter
I'm using MultiMap from Google Guava 12 like this:
我正在使用来自 Google Guava 12 的 MultiMap,如下所示:
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 ?
我该如何返回Map<Integer, Set<OccupancyType>>
?
回答by Xaerxess
Look at this issue and comment #2 by Kevin Bourrillion, head Guava dev:
看看这个 issue 并评论 #2 by Kevin Bourrillion,负责 Guava 开发:
You can double-cast the
Map<K, Collection<V>>
first to a raw Map and then to theMap<K, Set<V>>
that you want. You'll have to suppress an unchecked warning and you should comment at that point, "Safe because SetMultimap guarantees this."I may even update the SetMultimap javadoc to mention this trick.
您可以将
Map<K, Collection<V>>
第一个转换为原始 Map,然后转换为Map<K, Set<V>>
您想要的。您将不得不抑制未经检查的警告,并且您应该在此时注释,“安全,因为 SetMultimap 保证了这一点。” 我什至可能会更新 SetMultimap javadoc 来提及这个技巧。
So do unchecked cast:
所以做未经检查的演员:
@SuppressWarnings("unchecked") // Safe because SetMultimap guarantees this.
final Map<Integer, Set<OccupancyType>> mapOfSets =
(Map<Integer, Set<OccupancyType>>) (Map<?, ?>) pkgPOP.asMap();
EDIT:
编辑:
Since Guava 15.0 you can use helper methodto do this in more elegant way:
从 Guava 15.0 开始,您可以使用辅助方法以更优雅的方式执行此操作:
Map<Integer, Set<OccupancyType>> mapOfSets = Multimaps.asMap(pkgPOP);
回答by Louis Wasserman
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, the Multimap
supertype has to return a Map<K, Collection<V>>
, and because Map<K, Set<V>>
isn't a subtype of Map<K, Collection<V>>
, you can't override asMap()
to return a Map<K, Set<V>>
.
Map<K, Set<V>>
由于 Java 继承的工作方式,它无法返回 a 。本质上,Multimap
超类型必须返回 a Map<K, Collection<V>>
,并且由于Map<K, Set<V>>
不是 的子类型Map<K, Collection<V>>
,因此您不能覆盖asMap()
以返回 a Map<K, Set<V>>
。