如何转换MultiMap< Integer,Foo>映射<整数,设置< Foo>>用番石榴? [英] How can I convert MultiMap<Integer, Foo> to Map<Integer, Set<Foo>> using Guava?

查看:157
本文介绍了如何转换MultiMap< Integer,Foo>映射<整数,设置< Foo>>用番石榴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Guava 12中的MultiMap:

I'm using MultiMap from Google Guava 12 like this:

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

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

after inserting values into this multimap, I need to return:

Map<Integer, Set<OccupancyType>>

然而,当我这样做时:

return pkgPOP.asMap();

它给我回报

Map<Integer, Collection<OccupancyType>>

如何返回 Map< Integer,Set< OccupancyType>> 而不是?

推荐答案

看看本期和评论#2由Kevin Bourrillion ,负责人Guava dev:

Look at this issue and comment #2 by Kevin Bourrillion, head Guava dev:


您可以首先将 Map< K,Collection< V>> 重复投影到原始地图和
然后到你想要的 Map< K,Set< V>> 了。你必须禁止
未经检查的警告,你应该在那一点发表评论,安全,因为
SetMultimap保证这一点。
我甚至可以更新SetMultimap
javadoc提到这个技巧。

You can double-cast the Map<K, Collection<V>> first to a raw Map and then to the Map<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.

所以不选中演员:

@SuppressWarnings("unchecked") // Safe because SetMultimap guarantees this.
final Map<Integer, Set<OccupancyType>> mapOfSets = 
    (Map<Integer, Set<OccupancyType>>) (Map<?, ?>) pkgPOP.asMap();

编辑:

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

Since Guava 15.0 you can use helper method to do this in more elegant way:

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

这篇关于如何转换MultiMap&lt; Integer,Foo&gt;映射&lt;整数,设置&lt; Foo&gt;&gt;用番石榴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆