14

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;
}
Jake Walsh
  • 3,669
  • 5
  • 22
  • 28
  • Well, there often is no _best_ way and your way seems sensible to me. Do you have any problems with this? If not, I'd just stick with it (except that I'd add the generics to `new MultiMap()` too :) ). – Thomas Feb 17 '12 at 07:01

2 Answers2

24

...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));
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • They are indeed Guava and this is what I was looking for. My google skills seem to have failed me this time. Thanks – Jake Walsh Feb 17 '12 at 07:39
1

Your solution looks fine. You could initialize like this:

Multimap<T, K> multimap = new MultiMap(map1);

and then only iterate through the second map, however the complexity/speed is the same.

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66