Clone a HashMap – Shallow and Deep Copy

Learn to create clone of a HashMap in Java. We will see the java programs to create shallow copy and deep copy of a HashMap.

1. Creating a Shallow Copy of Map

We can create a shallow copy of a given HashMap in two ways. The first uses the clone() method, and the second is by iterating over the Map and copying the Map keys and values into a new Map.

We will be using the following Person class in the examples.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

  long id;
  String name;
  LocalDate dateOfBirth;
}

1.1. Using HashMap.clone()

The best way to create a shallow copy of Map is to use its clone() method. The keys and values themselves are not cloned and point to the same object in memory as in the original map.

HashMap<Integer, Person> personMap = new HashMap<>();

personMap.put(1, new Person(1l, "Alex", LocalDate.of(1990, 01, 01)));
personMap.put(2, new Person(2l, "Bob", LocalDate.of(1990, 02, 01)));

//Shallow clone
HashMap<Integer, Person> clonedMap = (HashMap<Integer, Person>) personMap.clone();

//Same as personMap
Assertions.assertTrue(Maps.difference(personMap, clonedMap).areEqual());

Let us change a value in the cloned Map and verify that the change in visible in the original map as well.

clonedMap.get(1).setName("Charles");

Assertions.assertEquals(clonedMap.get(1).getName(), personMap.get(1).getName());

1.2. Using Java 8 Stream

If we want little customization in values copied to cloned HashMap, or we simply want to modify the cloning process for individual key-value pairs, then we can use Java 8 stream api.

In this approach, iterate over HashMap entry set using Stream, perform customization of values and then collect the pairs in a new HashMap.

Map<Integer, Person> clonedMapWithStream = personMap.entrySet()
    .stream()
    //perform customization
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Assertions.assertTrue(Maps.difference(personMap, clonedMapWithStream).areEqual());

2. Creating a Deep Copy of Map

The most effective way to deep-clone a Java object is serialization. The same applies to deep cloning a HashMap as well. Here, we are using Google Gson library to serialize the HashMap and deserialize it to create HashMap deep copy.

Gson gson = new Gson();
String jsonString = gson.toJson(personMap);

Type type = new TypeToken<HashMap<Integer, Employee>>(){}.getType();
HashMap<Integer, Employee> deepClonedMap = gson.fromJson(jsonString, type);

Assertions.assertTrue(Maps.difference(personMap, deepClonedMap).areEqual());

Now, if we change the content of keys of values in the first map, the second map keys and values would be unaffected.

deepClonedMap.get(1).setName("Charles");

Assertions.assertFalse(Maps.difference(personMap, deepClonedMap).areEqual());

Let me know if you have questions about clone a HashMap deep or create a shallow copy of a HashMap in Java.

Happy Learning !!

Source Code on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial