Guava MultiMap
已实现ImmutableListMultimap
和ImmutableSetMultimap
。鉴于我已经创建了一个 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 typeMap<K, List<V>>
, callMultimaps.asMap(ListMultimap)
instead.
所以只需使用 static helper methods for this in Multimaps
之一其中:
Returns
multimap.asMap()
, with its type corrected fromMap<K, Collection<V>>
toMap<K, List<V>>
.
关于java - 将 Guava ListMultimap 转换为 Java Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61206024/