Created
May 24, 2024 19:28
-
-
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
This file contains hidden or 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
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