Deep Merge Two Maps in Java

In this post, we show you how to deep merge two maps in Java.

The following MapUtils class provides deepMerge(Map dst, Map src) method to deep merge two maps. You can use this class as MapUtils class and it's a method as a utility method in your project.

import java.util.Map;

/**
 * Utility methods for maps.
 */
public final class MapUtils {

    private MapUtils() {
    }

    /**
     * Deep merges two maps
     *
     * @param dst the map where elements will be merged into
     * @param src the map with the elements to merge
     * @return a deep merge of the two given maps.
     */
    @SuppressWarnings("unchecked")
    public static Map deepMerge(Map dst, Map src) {
        if (dst != null && src != null) {
            for (Object key : src.keySet()) {
                if (src.get(key) instanceof Map && dst.get(key) instanceof Map) {
                    Map originalChild = (Map)dst.get(key);
                    Map newChild = (Map)src.get(key);
                    dst.put(key, deepMerge(originalChild, newChild));
                } else {
                    dst.put(key, src.get(key));
                }
            }
        }

        return dst;
    }
}

Comments