Search code examples
javahashmapguava

How to convert Guava HashMultmap to java.util.Map


I am trying to convert Guava Multimap<String ,Collection<String>> into Map<String, Collection<String>> but I get a syntax error when using Multimaps.asMap(multimap). Here is a code:

HashMultimap<String, Collection<String>> multimap = HashMultimap.create();
for (UserDTO dto : employees) {
    if (dto.getDepartmentNames() != null) {
        multimap.put(dto.getUserName().toString().trim(), dto.getDepartmentNames());
    }
}
Map<String, Collection<String>> mapOfSets = Multimaps.asMap(multimap);

Here is a screenshot of error: enter image description here

Can someone point out where I am doing a mistake?


Solution

  • Return type of Multimaps.asMap(multimap) is Map<String, <Set<Collection<String>>.

    Multimap can hold multiple values of the same key. Hence, when you want to convert from multimap to a map, you need to keep collection of values for each key, just in case, there is a key which appears twice in the map.

    If you want to convert from MultiMap to Map and make set sum on the values, you can do the following:

    Multimaps.asMap(multimap).entrySet().stream()
        .collect(Collectors.toMap(
                     Map.Entry::getKey,
                     e->e.getValue().stream()
                          .flatMap(Collection::stream).collect(toSet())));