I have two (say, map1 and map2) that may contain same set of keys but different values. For each matching keys in both I want to put the key and its corresponding values from both into a third Multimap. I've browsed through all related questions on StackOverFlow, non of them provides a concrete solution to the problem.
My question was marked duplicate of Combine two Maps into a MultiMap . My question seek to collect from a two different Guava HashMultimap (not java.util.Map) into a third Guava HashMultimap.
Multimap<String, Collection<ArrayList<Double>>> combineMaps(Multimap<String, ArrayList<Double>> map1, Multimap<String, ArrayList<Double>> map2) {
Collection<ArrayList<Double>> combinedList = new ArrayList<ArrayList<Double>>();
Collection<ArrayList<Double>> list1 = new ArrayList<ArrayList<Double>>();
Collection<ArrayList<Double>> list2 = new ArrayList<ArrayList<Double>>();
map1.forEach((key, value) -> {
if(map2.containsKey(key)) {
list1 = (map1.get(key));
list2 = (map2.get(key));
combinedList.addAll(list1);
combinedList.addAll(list2);
multimap.put(key, combinedList);
}
});
return multimap;
}
For example, if map1 contains the key-values pairs key1 = {2.0, 3.1}
keyb = {3.2, 0.8}
And map2 contains keyz = {2.7, 1.2}
keyb = {5.9, 7.6}
key1 = {3.1, 9.4}
The combinedMap would contain key1 = {2.0, 3.1, 3.1, 9.4}
keyb = {3.2, 0.8, 5.9, 7.6}
Note that keyz won't be saved into combinedMap because there is no occurence of keyz in map1.