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);
}
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
}
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