What is the best way to combine two Maps into a single Guava MultiMap in Java?
For example:
Then the resulting combined multimap would contain
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;
}
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.
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.
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.
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.
...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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With