Clone a Map in Java
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.
|
1 2 3 4 5 6 7 8 9 10 |
public static<K, V> Map<K, V> clone(Map<K, V> original) { Map<K, V> copy = new HashMap<>(); for (Map.Entry<K, V> entry: original.entrySet()) { copy.put(entry.getKey(), entry.getValue()); } return copy; } |
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.
|
1 2 3 4 5 6 |
public static<K, V> Map<K, V> clone(Map<K, V> original) { Map<K, V> copy = new HashMap<>(); copy.putAll(original); return copy; } |
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.
|
1 2 3 |
public static<K, V> Map<K, V> clone(Map<K, V> original) { return new HashMap<>(original); } |
4. Using Java 8
We can use Stream from Java 8 onwards to clone a map, as shown below:
|
1 2 3 4 5 6 |
public static<K, V> Map<K, V> clone(Map<K, V> original) { return original.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } |
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.
|
1 2 3 4 5 6 7 |
public static<K, V> Map<K, V> clone(Map<K, V> original) { Gson gson = new Gson(); String jsonString = gson.toJson(original); return gson.fromJson(jsonString, Map.class); } |
That’s all about cloning a Map in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)