5 ways to Clone a Map in Java

Write a Java program to create copy all of the mappings from the specified map to a new map. In other words, clone a Map in Java. Assume there are no mutable mappings in the map.

 

1. Naive

Simple solution is to iterate the map and call put(k, v) once for each mapping from key k to value v in the specified map.

 

Download   Run Code

 

2. Using putAll(Collection<? extends E> c)

Map.putAll() method can also be used to copy all mappings from the original map to an empty map.

 

Download   Run Code

 

3. Copy Constructor

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

 

Download   Run Code

 

4. Java 8

We can use Stream API from Java 8 onwards to clone a Map as shown below:

 

Download   Run Code

 

5. JSON

We can also use Google’s Gson library for Serialization and Deserialization of Map objects. The idea is to convert the Map to a JSON String and then convert the JSON String back to new Map Object. This works as the serialized object holds no reference to the original object on deserialization.

 

Download

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of