Recursive merging of Java – N-level mappings

Is there any way to deeply merge maps in Java? I've read some posts about it, but most solutions seem to deal with only one level of consolidation or boring

My data structure (using JSON strings to represent maps) looks similar to:

{ name: "bob",emails: { home: "bob@home.com",work : "bob@work.com" } }

Ideally, if I have another map

{ emails: { home2: "bob@home2.com" } }

When combined with the first map, it will look like

{ name: "bob",work : "bob@work.com",home2: "bob@home2.com } }

I can guarantee that all my maps are < string, Object > Is there an out of the box solution? I really want to avoid writing a pile of recursive or iterative code for very nested or large objects

Solution

Improved version: This gist

This is a way to deeply merge Java maps:

// This is fancier than Map.putAll(Map)
private static 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 if (newMap.get(key) instanceof List && original.get(key) instanceof List) {
            List originalChild = (List) original.get(key);
            List newChild = (List) newMap.get(key);
            for (Object each : newChild) {
                if (!originalChild.contains(each)) {
                    originalChild.add(each);
                }
            }
        } else {
            original.put(key,newMap.get(key));
        }
    }
    return original;
}

Applies to nested maps, objects, and object lists Please enjoy

(Disclaimer: I'm not a java developer!)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>