How to clone 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.

Read More : A guide to cloning in Java

1. Clone HashMap – shallow copy

1.1. HashMap clone() method

The best way to create shallow clone of hashmap is to use it’s clone() method. It returns a shallow copy of the map. The keys and values themselves are not cloned; and point to same object in memory as in original map.

import java.time.LocalDate;
import java.util.HashMap;

public class JavaHashMapCloningExample 
{
    @SuppressWarnings("unchecked")
    public static void main(String[] args) 
    {
        HashMap<Integer, Employee> employeeMap = new HashMap<>();
        
        employeeMap.put(1, new Employee(1l, "Alex", LocalDate.of(1990, 01, 01)));
        employeeMap.put(2, new Employee(2l, "Bob", LocalDate.of(1990, 02, 01)));
        
        //Shallow clone
        HashMap<Integer, Employee> clonedMap = (HashMap<Integer, Employee>) employeeMap.clone(); 

        //Same as employeeMap
        System.out.println(clonedMap);
        
        System.out.println("\nChanges reflect in both maps \n");
        
        //Change a value is clonedMap
        clonedMap.get(1).setName("Charles");
        
        //Verify content of both maps
        System.out.println(employeeMap);
        System.out.println(clonedMap);
    }
}

Program output.

{1=Employee [id=1, name=Alex, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}

Changes reflect in both maps 

{1=Employee [id=1, name=Charles, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}
{1=Employee [id=1, name=Charles, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}

1.2. Clone HashMap using Java 8 Stream API

If you want little customization in values copied to cloned HashMap, or you 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 entryset using stream api, perform customization of values and then collect the pairs in a new HashMap.

HashMap<Integer, Employee> employeeMap = new HashMap<>();

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

// Shallow clone
Map<Integer, Employee> clonedMap = employeeMap.entrySet()
                                    .stream()
                                    //perform customization
                                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

// Same as employeeMap
System.out.println(clonedMap);

Program output.

{1=Employee [id=1, name=Alex, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}

2. How to deep clone HashMap

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

HashMap<Integer, Employee> employeeMap = new HashMap<>();
        
employeeMap.put(1, new Employee(1l, "Alex", LocalDate.of(1990, 01, 01)));
employeeMap.put(2, new Employee(2l, "Bob", LocalDate.of(1990, 02, 01)));

//Deep clone
Gson gson = new Gson();
String jsonString = gson.toJson(employeeMap);

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

System.out.println(clonedMap);

//--------------------------------------

System.out.println("\nChanges DO NOT reflect in other map \n");

//Change a value is clonedMap
clonedMap.get(1).setName("Charles");

//Verify content of both maps
System.out.println(employeeMap);
System.out.println(clonedMap);

Program output.

{1=Employee [id=1, name=Alex, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}

Changes DO NOT reflect in other map

{1=Employee [id=1, name=Alex, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}
{1=Employee [id=1, name=Charles, dob=1990-01-01], 2=Employee [id=2, name=Bob, dob=1990-02-01]}

Let me know if you have question regarding how to deep clone a HashMap or create shallow copy of a HashMap in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.