user101 user101 -5 years ago 94
Java Question

Combine multiple Map<String,List> structs by joining lists with keys of the same name

What would be the cleanest way to do this?

I have

Map<String, List<String>> map1 = ...;
Map<String, List<String>> map2 = ...;
Map<String, List<String>> map3 = ...;

The maps all have the exact same keys, and no duplicate values. I want to append the Lists of map2 and map3 to the end of the list of map1, for each key.

This is how I am currently trying to do it:

Map<String, List<String>> conversions = new HashMap<String, List<String>>();
List<String> histList = new ArrayList<String>();

for(String key : map1.keySet()){

Answer Source

If you don't want to make a temporary list, you could directly add to list one, instead of replacing it.

for (String key: map1.keySet()) { //iterate over all the keys
    map1.get(key).addAll(map2.get(key)); //add all the values in map 2 to map 1
    map1.get(key).addAll(map3.get(key)); //add all the values in map 3 to map 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download