How to Serialize HashMap in Java?

08 Dec, 2020
Serialization is the process by which we convert an object into a stream of bytes and store these bytes in file systems/databases or put them on the network to move from one location to another.
Deserialization is the reverse process of serialization. Deserialization consists of retrieving the objects from the byte stream.
Hashmap: A HashMap stores items in key/value pairs, and we can access them by an index of another type (such as a string).
Now to serialize anything, you have to implement the java.io.Serializable interface and HashMap also implements the Serializable interface. Then after serializing the HashMap, we will learn how to deserialize the hashmap in Java.
Example 1: Serializing HashMap of String keys and String values
In this example, we are serializing HashMap, where keys and values are the strings. We are using writeObject() method of ObjectOutputStream to serialize HashMap in Java. In the following program, we save the hashmap content in a serialized newHashMap file. Once you run the following code, a newHashMap file will be created. This file is used for deserialization in the next upcoming program.
Java
// Java program on how to Serialize HashMap in Java  import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.util.HashMap;  public class HashMapExample1 {    public static void main(String[] args)    {        HashMap<String, String> foodType = new HashMap<>();          // storing data in HashMap        foodType.put("Burger", "Fastfood");        foodType.put("Cherries", "Fruit");        foodType.put("Fish", "Seafood");        foodType.put("Spinach", "Vegetables");        foodType.put("Chicken", "Protein-Rich");          // try catch block        try {            FileOutputStream myFileOutStream                = new FileOutputStream(                    "/Users/piyushkumar/Downloads/Java/newHashMap.txt");              ObjectOutputStream myObjectOutStream                = new ObjectOutputStream(myFileOutStream);              myObjectOutStream.writeObject(foodType);              // closing FileOutputStream and            // ObjectOutputStream            myObjectOutStream.close();            myFileOutStream.close();        }        catch (IOException e) {            e.printStackTrace();        }    }}
Output
In the example above, we serialized the HashMap of foodType using the writeObject () method. 
Run this program and see in your file system that a file called “newHashMap.txt” is created and the entire HashMap (in encoded form) is saved. Now, we will learn how to read this file and deserialize the HashMap.
Example 2: Deserializing HashMap of string keys and values
It’s important to note that we can only store the deserialized HashMap into the reference variable of HashMap or any of its parent class. Other than that java.lang.ClassCastException Exception will occur.
Java
// Deserializing HashMap in Java  import java.io.FileInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;  public class HashMapExample2 {    public static void main(String[] args)    {        HashMap<String, String> newHashMap = null;          try {            FileInputStream fileInput = new FileInputStream(                "/Users/piyushkumar/Downloads/Java/newHashMap.txt");              ObjectInputStream objectInput                = new ObjectInputStream(fileInput);              newHashMap = (HashMap)objectInput.readObject();              objectInput.close();            fileInput.close();        }          catch (IOException obj1) {            obj1.printStackTrace();            return;        }          catch (ClassNotFoundException obj2) {            System.out.println("Class not found");            obj2.printStackTrace();            return;        }          System.out.println("Deserializing  HashMap..");          // Displaying content in "newHashMap.txt" using        // Iterator        Set set = newHashMap.entrySet();        Iterator iterator = set.iterator();          while (iterator.hasNext()) {            Map.Entry entry = (Map.Entry)iterator.next();              System.out.print("key : " + entry.getKey()                             + " & Value : ");            System.out.println(entry.getValue());        }    }}}
Output
Java-HashMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array