Are you looking for something like this:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MapUnion {
/**
* This method adds all entries in all maps and return it as single map. It
* takes Collection of elements of type Map<K, V>
*
* @param maps - the Collection of maps, to sum all the entries
* @return map containig "union" of all entries from all of the supplied maps
*/
public <K, V> Map<K, V> unionAllMaps(Collection<Map<K, V>> maps) {
return unionAllMaps(maps.toArray(new Map[maps.size()]));
}
/**
* This method adds all entries in all maps and return it as single map. It
* takes any numner of elements of type Map<K, V>. You can invoke it using
* eg unionAllMaps(map1, map2, map3); the ... denotes, that all parameters
* will be automatically converted to an array
*
* @param maps - the Array of maps, to sum all the entries
* @return map containig "union" of all entries from all of the supplied maps
*/
public <K, V> Map<K, V> unionAllMaps(Map<K, V>... maps) {
HashMap<K, V> union = new HashMap<K, V>();
for (Map<K, V> map : maps) {
union.putAll(map);
}
return union;
}
public static void main(String[] args) {
new MapUnion().test();
}
public void test() {
HashMap<Integer, String> map1 = new HashMap<Integer, String>();
map1.put(1, "1");
map1.put(2, "2");
HashMap<Integer, String> map2 = new HashMap<Integer, String>();
map1.put(2, "2");
map1.put(3, "3");
ArrayList<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>();
maps.add(map1);
maps.add(map2);
Map<Integer, String> union = unionAllMaps(maps);
System.out.println(union);
}
}
will print:
{1=1, 2=2, 3=3}
But what should happen if there are same keys with different values in these maps? In this approach, the last value will overwrite previous one, but is this correct?