Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()){
    histList.addAll(map1.get(key));
    histList.addAll(map2.get(key));
    histList.addAll(map3.get(key));
    conversions.put(key,histList);
}
like image 517
user101 Avatar asked Jun 16 '16 19:06

user101


1 Answers

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
}
like image 161
dustinroepsch Avatar answered Oct 20 '22 06:10

dustinroepsch