Skip to content

Instantly share code, notes, and snippets.

@dlabey
Created May 24, 2024 19:28
Show Gist options
  • Save dlabey/830266616ac4c1590273936677f59285 to your computer and use it in GitHub Desktop.
Save dlabey/830266616ac4c1590273936677f59285 to your computer and use it in GitHub Desktop.
Deep Merge a Java Object when the original does not have the value
import java.util.List;
import java.util.Map;
class Utils {
private Utils() {
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Map deepMerge(Map original, Map newMap) {
for (Object key : newMap.keySet()) {
if (newMap.get(key) instanceof Map newChild && original.get(key) instanceof Map originalChild) {
original.put(key, deepMerge(originalChild, newChild));
} else if (newMap.get(key) instanceof List newChild && original.get(key) instanceof List originalChild) {
for (Object each : newChild) {
if (!originalChild.contains(each)) {
originalChild.add(each);
}
}
} else {
original.putIfAbsent(key, newMap.get(key));
}
}
return original;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment