Null-safe merge of two maps. - Java Collection Framework

Java examples for Collection Framework:Map

Description

Null-safe merge of two maps.

Demo Code


//package com.java2s;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    /**//from   ww  w. j  a  v a  2s .c om
     * Null-safe merge of two maps. If both parameters are null it returns empty map.
     * If one of the maps is null, it returns the other one. If a key is present in two maps,
     * the value in the merged map will be taken from the overriding map.
     * @param overridingMap The map overriding values in the base map
     * @param baseMap The base map
     * @return merged map
     */
    public static Map<Object, Object> mergeMaps(
            Map<Object, Object> overridingMap, Map<Object, Object> baseMap) {
        Map<Object, Object> mergedMap = new LinkedHashMap<>();

        if (baseMap == null && overridingMap != null) {
            mergedMap.putAll(overridingMap);
        } else if (overridingMap == null && baseMap != null) {
            mergedMap.putAll(baseMap);
        } else if (overridingMap != null) {
            mergedMap.putAll(baseMap);
            mergedMap.putAll(overridingMap);
        }
        return mergedMap;
    }
}

Related Tutorials