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



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.



1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

newest oldest most voted
Notify of
Maksym Kmets

The last is a hell)))