将 Guava ListMultimap 转换为 Java 地图
Convert Guava ListMultimap to Java Map
Guava MultiMap
有实现 ImmutableListMultimap
和 ImmutableSetMultimap
。鉴于我已经创建了一个 ImmutableListMultimap<String, Anything>
实例,我如何将其转换为 java.util.Map<String, List<Anything>>
?
asMap()
方法return一个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 commons-collections 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.
所以只需使用静态 helper methods for this in Multimaps
之一:
Returns multimap.asMap()
, with its type corrected from Map<K, Collection<V>>
to Map<K, List<V>>
.
Guava MultiMap
有实现 ImmutableListMultimap
和 ImmutableSetMultimap
。鉴于我已经创建了一个 ImmutableListMultimap<String, Anything>
实例,我如何将其转换为 java.util.Map<String, List<Anything>>
?
asMap()
方法return一个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 commons-collections 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 typeMap<K, List<V>>
, callMultimaps.asMap(ListMultimap)
instead.
所以只需使用静态 helper methods for this in Multimaps
之一:
Returns
multimap.asMap()
, with its type corrected fromMap<K, Collection<V>>
toMap<K, List<V>>
.