Java Map Merge merge(final Map lhs, final Map rhs)

Here you can find the source of merge(final Map lhs, final Map rhs)

Description

Clones the lhs map and add all things from the rhs map.

License

Apache License

Parameter

Parameter Description
lhs the first map
rhs the second map
K the map key type
V the map value type

Return

the merged map

Declaration

public static <K, V> Map<K, V> merge(final Map<K, V> lhs, final Map<K, V> rhs) 

Method Source Code


//package com.java2s;
/*/*from   w  w  w .j  ava2  s.  com*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

import java.util.HashMap;
import java.util.Map;

public class Main {
    /**
     * Clones the lhs map and add all things from the rhs map.
     *
     * @param lhs
     *            the first map
     * @param rhs
     *            the second map
     * @param <K>
     *            the map key type
     * @param <V>
     *            the map value type
     * @return the merged map
     */
    public static <K, V> Map<K, V> merge(final Map<K, V> lhs, final Map<K, V> rhs) {

        Map<K, V> result = null;

        if (lhs == null || lhs.size() == 0) {
            result = copy(rhs);
        } else if (rhs == null || rhs.size() == 0) {
            result = copy(lhs);
        } else {
            result = copy(lhs);
            result.putAll(rhs);
        }

        return result;
    }

    /**
     * Clones a map.
     * 
     * @param source
     *            the Map to clone
     * @param <K>
     *            the map key type
     * @param <V>
     *            the map value type
     * @return the cloned map
     */
    public static <K, V> Map<K, V> copy(final Map<K, V> source) {

        if (source == null) {
            return null;
        }

        final Map<K, V> result = new HashMap<K, V>();
        result.putAll(source);
        return result;
    }
}

Related

  1. deepMerge(Map dst, Map src)
  2. deepMerge(Map m1, Map m2)
  3. deepMerge(Map original, Map newMap)
  4. merge(final Map map1, final Map map2)
  5. merge(final Map... maps)
  6. merge(final Map> targetContext, final Map> newContext)
  7. merge(List> list)