Given a map, the task is to clone that map.
Following are the 5 different ways to Clone a
Map in Java.
Example:
{1=Geeks, 2=For, 3=Geeks}
Method 1: Naive method
1. Create an object for the class map.
2. Put the elements into the map using the put() method.
3. Again create another object for the class map.
4. Now finally iterate the map and call put method to clone the initial map.
Below is the implementation of the above approach:
Implementation:
Output:
{1=Geeks, 2=For, 3=Geeks}
Method 2: Using putAll().
1. Create an object for the class map.
2. Put the elements into the map using the put() method.
3. Again create another object for the class map.
4. Now finally use putAll() method to clone the initial map.
Below is the implementation of the above approach:
Implementation:
Output:
{1=Geeks, 2=For, 3=Geeks}
Method 3: Copy Constructor.
1. Create an object for the class map.
2. Put the elements into the map using the put() method.
3. Again create another object for the class map.
4. Now finally use the copy constructor(It is a special constructor used for creating a new object as a copy of an existing object) to clone the initial map.
Below is the implementation of the above approach:
Implementation:
Output:
{1=Geeks, 2=For, 3=Geeks}
Method 4: Java 8
1. Create an object for the class map.
2. Put the elements into the map using the put() method.
3. Again create another object for the class map.
4. Now finally use Stream API from Java 8 to clone the initial map.
Below is the implementation of the above approach:
Implementation:
Output:
{1=Geeks, 2=For, 3=Geeks}
Explanation:It is also similar to above methods, but here we use Stream API from java 8 to clone the original map.
Method 5: JSON
1. Create an object for the class map.
2. Put the elements into the map using the put() method.
3. Again create another object for the class map.
4. Now finally use Google's GSON library to clone the initial map.
Below is the implementation of the above approach:
Implementation:
Output:
{1=Geeks, 2=For, 3=Geeks}
Explanation:It is also similar to the above methods, but here we use Google's GSON library to clone the original map. Here initially we convert Map to a JSON string and later we convert that string to a new map.