How to Serialize HashMap in Java?
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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.
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.