tkruse
tkruse

Reputation: 10685

Convert Guava ListMultimap to Java Map

Guava MultiMap has implementations ImmutableListMultimap and ImmutableSetMultimap. Given that I have created an ImmutableListMultimap<String, Anything> instance, how can I convert that into a java.util.Map<String, List<Anything>>?

The asMap() method return a java.util.Map<String, Collection<Anything>>, but that cannot be cast to java.util.Map<String, List<Anything>>.

The best I have now is

 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()));

but that does not look ideal. Given that the instance variable is of type ListMultimap, shouldn't there be a convenient method to represent it as a Map<..., List>?

Apache commons-collections ArrayListValuedHashMap has the same issue.

Upvotes: 2

Views: 1676

Answers (1)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

ListMultimap.asMap() docs mention

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.

So just use one of static helper methods for this in Multimaps which:

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

Upvotes: 5

Related Questions