java - 将 Guava ListMultimap 转换为 Java Map

标签 java guava multimap apache-commons-collection

Guava MultiMap已实现ImmutableListMultimapImmutableSetMultimap 。鉴于我已经创建了一个 ImmutableListMultimap<String, Anything>例如,我如何将其转换为 java.util.Map<String, List<Anything>>

asMap()方法返回 java.util.Map<String, Collection<Anything>> ,但不能转换为 java.util.Map<String, List<Anything>> .

我现在拥有的最好的是

 final Map<String, Collection<Anything>> listMultimap = multimap.asMap();
 // convert to Map<String, List<>>
 final Map<String, List<Anything>> listMap = listMultimap.entrySet().stream()
     .collect(Collectors.toMap(
                  Map.Entry::getKey, 
                  e -> (List<Anything>) e.getValue()));

但这看起来并不理想。鉴于实例变量是ListMultimap类型,难道不应该有一个方便的方法将其表示为 Map<..., List>

Apache 公共(public)集合 ArrayListValuedHashMap有同样的问题。

最佳答案

ListMultimap.asMap() 文档提到

Note: The returned map's values are guaranteed to be of type List. To obtain this map with the more specific generic type Map<K, List<V>>, call Multimaps.asMap(ListMultimap) instead.

所以只需使用 static helper methods for this in Multimaps 之一其中:

Returns multimap.asMap(), with its type corrected from Map<K, Collection<V>> to Map<K, List<V>>.

关于java - 将 Guava ListMultimap 转换为 Java Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61206024/

相关文章:

java - ActiveMQ 从队列中获取所有消息

java - Apache FOP 可以在 Android 上运行吗?

java - Apaches Ignite 不会序列化/反序列化 Guavas LoadingCache

用于存储思维导图等结构的数据库

java - Tomcat 没有看到我的 servlet

java - 带有 fragment 和 Activity 的 FragmentActivity TabHost

java - 使用 Guava 的 Resources.readLines 从 HTTP 服务读取

java - 使用缓存作为数据库前面的一层

java - 合并两个 Guava 多重贴图

c++ - 按字母顺序打印 std::multimap 键和值