Java Utililty Methods Map Copy

List of utility methods to do Map Copy

Description

The list of methods to do Map Copy are organized into topic(s).

Method

MapcopyAndRemove(Map map, K key)
copy And Remove
Map<K, V> copy = new HashMap<K, V>(map);
copy.remove(key);
return copy;
Map>copyDeep(Map> data)
Copies the given Map containing another Map into a new Map .
final int size = data.size();
switch (size) {
case 0:
    return Collections.emptyMap();
case 1:
    final A key = data.keySet().iterator().next();
    return Collections.singletonMap(key, copy(data.get(key)));
default:
...
voidcopyEntries(Map aSource, Map aTarget)
Recursively copies config entry map from the source to the target.
for (Iterator iter = aSource.entrySet().iterator(); iter.hasNext();) {
    Map.Entry entry = (Map.Entry) iter.next();
    Object key = entry.getKey();
    Object value = entry.getValue();
    if (value instanceof Map) {
        Map newCopy = new HashMap();
        copyEntries((Map) value, newCopy);
        aTarget.put(key, newCopy);
...
MapcopyExcludingKeys(Map map, Set excludedKeys)
Returns new Map
Map<K, V> resultMap = new HashMap<>();
for (Entry<K, V> entry : map.entrySet()) {
    if (false == excludedKeys.contains(entry.getKey())) {
        resultMap.put(entry.getKey(), entry.getValue());
return resultMap;
voidcopyHashMap(HashMap map1, HashMap map2)
this works only for hashmaps having similar keysets or copying into new hashmap
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)); 
                break;
MapcopyLowerCaseMap(Map map)
copy Lower Case Map
if (map == null) {
    return null;
HashMap<String, Object> keyMap = new HashMap<String, Object>();
Iterator<?> keys = map.keySet().iterator();
while (keys.hasNext()) {
    String key = (String) keys.next();
    Object value = map.get(key);
...
voidcopyMap(Map from, Map to)
copy Map
if (from == null || to == null)
    return;
for (Object key : from.keySet()) {
    to.put(key, from.get(key));
voidcopyMap(Map sourceMap, Map targetMap)
copy Map
targetMap.putAll(sourceMap);
MapcopyMap(Map m)
copy Map
return new HashMap<>(m);
MapcopyMap(Map m)
copy Map
return new HashMap<K, V>(m);