Created
October 9, 2012 13:28
-
-
Save aslakhellesoy/3858814 to your computer and use it in GitHub Desktop.
Merge two maps in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is fancier than Map.putAll(Map) | |
public Map deepMerge(Map original, Map newMap) { | |
for (Object key : newMap.keySet()) { | |
if (newMap.get(key) instanceof Map && original.get(key) instanceof Map) { | |
Map originalChild = (Map) original.get(key); | |
Map newChild = (Map) newMap.get(key); | |
original.put(key, deepMerge(originalChild, newChild)); | |
} else { | |
original.put(key, newMap.get(key)); | |
} | |
} | |
return original; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out this
I use
temp
variables because -often in my case- collections are originally immutable.