Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 838
Jake Walsh Avatar asked Feb 17 '12 06:02

Jake Walsh


People also ask

How can I merge two maps?

Alternatively, we can use Stream#concat() function to merge the maps together. This function can combine two different streams into one. As shown in the snippet, we are passed the streams of map1 and map2 to the concate() function and then collected the stream of their combined entry elements.

Can you combine two maps in Minecraft?

You can't merge maps. The only way to fully explore a map is to manually explore all the terrain shown on the map while holding that map.

How can I combine two Hashmap objects containing the different types?

Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example. You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.

Can we add two maps in C++?

map<int, int> map1 = { {1, 10}, {2, 20} }; map<int, int> map2 = { {3, 30}, {4, 40} }; 3) Using insert function:- In order to merge two maps, we will use the built-in function insert. It will insert map2 in map1 from beginning till end.


2 Answers

...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));
like image 64
Louis Wasserman Avatar answered Oct 16 '22 18:10

Louis Wasserman


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.

like image 24
Bernd Elkemann Avatar answered Oct 16 '22 18:10

Bernd Elkemann