Here you can find the source of copyMap(Map
Parameter | Description |
---|---|
oMap | original map instance to copy |
K | map key type |
V | map value type |
@SuppressWarnings("unchecked") public static <K, V> Map<K, V> copyMap(Map<K, V> oMap)
//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; } }