Java Map Copy copyHashMap(HashMap map1, HashMap map2)

Here you can find the source of copyHashMap(HashMap map1, HashMap map2)

Description

this works only for hashmaps having similar keysets or copying into new hashmap

License

Open Source License

Parameter

Parameter Description
map1 a parameter
map2 a parameter
K a parameter
V a parameter

Declaration

public static <K, V> void copyHashMap(HashMap<K, V> map1, HashMap<K, V> map2) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {
    /**/*from   w ww. j  av a2 s.c  om*/
     * this works only for hashmaps having similar keysets
     * or
     * copying into new hashmap
     * @param map1
     * @param map2
     * @param <K>
     * @param <V>
     */
    public static <K, V> void copyHashMap(HashMap<K, V> map1, HashMap<K, V> map2) {
        Set<K> keySet1 = map1.keySet();
        Set<K> keySet2 = map2.keySet();

        Iterator<K> iter1 = keySet1.iterator();

        if (map2.size() == 0) {
            while (iter1.hasNext()) {
                K item1 = iter1.next();
                map2.put(item1, map1.get(item1));
            }
        }

        else {
            while (iter1.hasNext()) {
                K item1 = iter1.next();
                Iterator<K> iter2 = keySet2.iterator();
                while (iter2.hasNext()) {
                    K item2 = iter2.next();
                    if (item2.equals(item1)) {
                        map1.put(item1, map2.get(item1)); // copies values of map2 into map1
                        break;
                    }
                }

            }
        }

    }
}

Related

  1. copy(Map src, Map dst)
  2. copyAndRemove(Map map, K key)
  3. copyDeep(Map> data)
  4. copyEntries(Map aSource, Map aTarget)
  5. copyExcludingKeys(Map map, Set excludedKeys)
  6. copyLowerCaseMap(Map map)
  7. copyMap(Map from, Map to)
  8. copyMap(Map sourceMap, Map targetMap)
  9. copyMap(Map m)