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

1. Naive solution

A 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 Map.putAll() method

We can also use the Map.putAll(Collection<? extends E> c) method to copy all mappings from the original map to an empty map.

Download  Run Code

3. Using 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. Using Java 8

We can use Stream from Java 8 onwards to clone a map, as shown below:

Download  Run Code

5. Using 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 a new map object. This works as the serialized object holds no reference to the original object on deserialization.

Download Code

That’s all about cloning a Map in Java.