Java Map Copy copyMap(Map oMap)

Here you can find the source of copyMap(Map oMap)

Description

Makes a true copy of provided oMap instance.

License

Apache License

Parameter

Parameter Description
oMap original map instance to copy
K map key type
V map value type

Return

copy of oMap , or null if original map is null

Declaration

@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> copyMap(Map<K, V> oMap) 

Method Source Code

//package com.java2s;
/*//from www.j  a v  a 2 s.  c o m
 * Copyright 2014-2018 JKOOL, LLC.
 *
 * Licensed 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 {
    /**
     * Makes a true copy of provided {@code oMap} instance. Map copy instance entries do not have references to original
     * map, so altering copy map entries will not affect original map.
     * <p>
     * Note: copied map is always a {@link java.util.HashMap}.
     *
     * @param oMap
     *            original map instance to copy
     * @param <K>
     *            map key type
     * @param <V>
     *            map value type
     * @return copy of {@code oMap}, or {@code null} if original map is {@code null}
     */
    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> copyMap(Map<K, V> oMap) {
        if (oMap == null) {
            return null;
        }

        Map<K, V> cMap = new HashMap<>(oMap.size());

        for (Map.Entry<K, V> ome : oMap.entrySet()) {
            V oVal = ome.getValue();
            if (oVal instanceof Map) {
                oVal = (V) copyMap((Map<K, V>) oVal);
            }
            cMap.put(ome.getKey(), oVal);
        }

        return cMap;
    }
}

Related

  1. copyLowerCaseMap(Map map)
  2. copyMap(Map from, Map to)
  3. copyMap(Map sourceMap, Map targetMap)
  4. copyMap(Map m)
  5. copyMap(Map m)
  6. copyMap(Map map)
  7. copyMap(Map m)
  8. copyMap(Object object)
  9. copyMapButFailOnNull(Map entries)