The Wayback Machine - https://web.archive.org/web/20240717024413/https://www.geeksforgeeks.org/how-to-copy-one-hashmap-to-another-hashmap-in-java/
Open In App

How to Copy One HashMap to Another HashMap in Java?

Last Updated : 04 Sep, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.  This class makes no guarantees as to the order of the map. To use this class and its methods, you need to import java.util.HashMap package or its superclass.

Given a HashMap, there are three ways one can copy the given HashMap to another:

  1. By normally iterating and putting it to another HashMap using put(k, v) method.
  2. Using putAll() method.
  3. Using copy constructor.
  4. Using assignment operator.

Method 1: By normally iterating and putting it to another HashMap using put(k, v) Method.

A simple solution is to iterate through the map and use put(Key,Value) once for each mapping key and value in the another Map.

Java




// Java program to iterate through the
// first map and put it in the second map
 
import java.util.HashMap;
import java.util.Map;
 
class GFG {
    public static <K, V> Map<K, V>
    copyMap(Map<K, V> original)
    {
 
        Map<K, V> second_Map = new HashMap<>();
 
        // Start the iteration and copy the Key and Value
        // for each Map to the other Map.
        for (Map.Entry<K, V> entry : original.entrySet()) {
 
            // using put method to copy one Map to Other
            second_Map.put(entry.getKey(),
                           entry.getValue());
        }
 
        return second_Map;
    }
 
    public static void main(String[] args)
    {
 
        Map<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
         
        // copyMap method would copy the original
        // hashMap to second_Map
        Map<String, Integer> second_Map = copyMap(hashMap);
       
        System.out.println(second_Map);
    }
}


Output

{A=1, B=2, C=3}

Method 2: Using putAll(k, v) Method.

Map.putAll(k,v) method is used to copy one HashMap to another empty HashMap.

Syntax:

new_hash_map.putAll(exist_hash_map)

Parameters: The method takes one parameter exist_hash_map that refers to the existing map we want to copy from.

Return Value: The method does not return any values.

Exception: The method throws NullPointerException if the map we want to copy from is NULL.

Java




// Java program to copy hashmap to
// another hashmap using putAll() method
 
import java.util.HashMap;
import java.util.Map;
 
class GFG {
    public static <K, V> Map<K, V>
    copyMap(Map<K, V> original)
    {
 
        Map<K, V> second_map = new HashMap<>();
 
        // using putAll method to copy from original Map to
        // second_map
        second_map.putAll(original);
 
        return second_map;
    }
 
    public static void main(String[] args)
    {
 
        Map<String, Integer> hashMap = new HashMap<>();
 
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
 
        // copyMap method would copy the original
        // hashMap to second_Map
        Map<String, Integer> second_map = copyMap(hashMap);
       
        System.out.println(second_map);
    }
}


Output

{A=1, B=2, C=3}

Method 3: Using copy constructor.

It is one of the shortest and easiest ways to copy one HashMap to another.

We can use a copy constructor to copy a map which is a special constructor for creating a new object as a copy of an existing object.

Java




import java.util.HashMap;
import java.util.Map;
 
class GFG {
   
    // using copy constructor to return the original map
    // and then copy it in second_map
    public static <K, V> Map<K, V> copyMap(Map<K, V> original)
    {
       // constructor by passing original hashmap
       // in the parameter returns the new hashmap
       // with the copied content of the original one
        return new HashMap<>(original);
    }
 
    public static void main(String[] args)
    {
 
        Map<String, Integer> hashMap = new HashMap<>();
 
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
         
        // copyMap method would copy the original
        // hashMap to second_Map
        Map<String, Integer> second_map = copyMap(hashMap);
 
        System.out.println(second_map);
    }
}


Output

{A=1, B=2, C=3}

Method 4 : Using Assignment Operator

In java, if both the objects are same then we can easily copy or assign one object elements to other by simply using assignment operator “=”.

Java




/*package whatever //do not write package name here */
 
import java.util.*;
 
class GFG {
    public static void main (String[] args) {
         Map<String, Integer> hashMap = new HashMap<>();
 
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
         
        // using assigning operator
        // hashMap to second_Map
        Map<String, Integer> second_map = hashMap;
 
        System.out.println(second_map);
    }
}


Output :

{A=1, B=2, C=3}



Similar Reads

Copy Elements of One Java Vector to Another Vector in Java
Vector is similar to arrays but is growable also, or we can say no fixed size is required. Previously vector was a part of legacy classes but now it is part of Collections. It also implements a List interface, so we can use any method of list interface on vectors also. Syntax : Vector&lt;Integer&gt; gfg=new Vector&lt;&gt;(); Ways To copy elements o
3 min read
Converting Integer-String HashMap to String-Array-Integer HashMap in Java
Efficient Conversion of a HashMap&lt;Integer, String&gt; into another HashMap&lt;String, Integer[]&gt; involves organizing integer keys based on their corresponding string values. Here's a concise and efficient Java method to accomplish this transformation, focusing on clear and straightforward implementation. Step-by-Step Implementation of Convers
3 min read
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
Copy Elements of One ArrayList to Another ArrayList in Java
It is the implementation class of List Interface. It allows duplicated objects/elements and as well as maintains the insertion order. You can get the element present inside the ArrayList by the index of it now you need to pass it into the getting (index) method. You can add the elements into ArrayList using the add() method. Syntax: ArrayList Initi
7 min read
How to Copy Key-Value Pairs from One TreeMap to Another in Java?
In Java, a TreeMap is a Map implementation that stores key-value pairs in a red-black tree structure. It allows insertions and deletions of key-value pairs due to its tree implementation. These operations take O(log n) time on average. In this article, we will be learning how to copy key-value pairs from one TreeMap to another in Java. Syntax:newTr
2 min read
How to Copy Elements from One PriorityQueue to Another in Java?
In Java, a priority queue is a data structure that allows the users to store data based on their priority. In this article, we will learn how to copy elements from one priority queue to another in Java. Example Input: PriorityQueue original ={1,2,3,4,5}Output: PriorityQueue Copy ={1,2,3,4,5}Copy elements from One PriorityQueue to AnotherTo copy ele
2 min read
How to Copy or Append HashSet to Another HashSet in Java?
HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements' order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. We can copy or append a HashSet to another HashSet. There is a couple of ways to copy HashSet or
4 min read
Java Program to Copy the Map Content to Another Hashtable
HashMap and Hashtable are used to store data in key and value form using a hashing technique to store unique keys. To copy Map content to another Hashtable in Java putAll() method is used. putAll() method: The method copies all the mappings from the specified hashmap to the hashtable. These mappings replace any mappings that this hash table had for
2 min read
How to Copy Map Content to Another Hashtable in Java?
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. HashMap and Hashtable are used to store data in key and value form using a has
2 min read
Using Semaphore to Protect More than One Copy of a Resource in Java
A semaphore work on the concepts of permits. A semaphore is initialized with a certain number of permits. The number of permits is equal to the number of shared resources available. When a thread wants to access a shared resource, it acquires the permit and when done accessing the shared resource, it releases the permit. Illustration: Illustration
10 min read
three90RightbarBannerImg