Search code examples
javaguavamultimap

Combine two Maps into a MultiMap


What is the best way to combine two Maps into a single Guava MultiMap in Java?

For example:

  • Map1 contains (1, a) and (2, b)
  • Map2 contains (2, c) and (3, d)

Then the resulting combined multimap would contain

  • (1, {a}), (2, {b, c}), and (3, {d})

This is my current solution:

Multimap<T, K> combineMaps(Map<T, K> map1, Map<T, K> map2) {
    Multimap<T, K> multimap = new MultiMap();
    for (final Map.Entry<T, K> entry : map1.entrySet()) {
        multimap.put(entry.getKey(), entry.getValue());
    }
    for (final Map.Entry<T, K> entry : map2.entrySet()) {
        multimap.put(entry.getKey(), entry.getValue());
    }
    return multimap;
}

Solution

  • ...What sort of multimaps are these? Are they from Guava, or some other library?

    In Guava, you could do

    multimap.putAll(Multimaps.forMap(map1));
    multimap.putAll(Multimaps.forMap(map2));