HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java HashMap / How to clone HashMap – Shallow and Deep Copy

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java HashMap

  • HashMap – Introduction
  • HashMap – How it works
  • HashMap – Custom Key Design
  • HashMap – Synchronize HashMap
  • HashMap – Merge HashMaps
  • HashMap – Compare HashMaps
  • HashMap – Iterations
  • HashMap – Cloning

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces