Skip to main content

Serialize HashMap in Java

How to serialize HashMap in Java

In this article, we will learn about how to serialize HashMap in java. To serialize anything, it must implement java.io.Serializable interface and HashMap also implements the Serializable interface. After, serializing the HashMap, we will learn how to deserialize HashMap in java.
If you are new to HashMap, I suggest you to read first All about HashMap in Java.
"Serialization is a process in which we convert the object into the byte stream and this stream of bytes can be stored into the file system/databases or can be placed onto the network for transmission from one place to another.
Deserialization is the reverse process of the Serialization. Deserialization is to get back the objects from the byte stream."

Content of the Article

How to serialize HashMap of string keys and values?

Let's start with a very basic example to serialize HashMap, where keys and values are the strings. We can use the writeObject() method of ObjectOutputStream to serialize HashMap in Java.

Java Serialize HashMap Example 1: Serialize HashMap of String keys and String values.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
       HashMap<String, String> cities = new HashMap<>();
       cities.put("Mumbai", "India");
       cities.put("Delhi", "India");
       cities.put("New York", "USA");
       cities.put("London", "England");
       cities.put("Beijing", "China");

       try {
           FileOutputStream fileOutputStream = new FileOutputStream("cities-file");
           ObjectOutputStream objectOutputStream 
                    = new ObjectOutputStream(fileOutputStream);

           objectOutputStream.writeObject(cities);

           objectOutputStream.close();
           fileOutputStream.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}
In the above example, we serialize HashMap of the city-country mappings using the writeObject() method. Run this program and see into your file system, a file named with the "cities-file" will be created and store the complete HashMap (In encoded form). Now, learn how to read that file and deserialize the HashMap.
Note : 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 would be raised.

Java Serialize HashMap Example 2: Deserialize HashMap of string keys and values

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("cities-file");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            HashMap<String, String> hashMap 
                = (HashMap<String, String>) objectInputStream.readObject();
            System.out.println(hashMap);

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
{Beijing=China, Delhi=India, New York=USA, London=England, Mumbai=India}

How to serialize HashMap of user-defined object values?

We can also serialize HashMap of user-defined objects, but remember that the user-defined object must implement the Serializable interface. Otherwise, java.io.NotSerializableException will be raised. In our previous example, we have serialized the HashMap of string keys and values and the String class implements Serializable interface.
"The java.io.Serializable interface is a marker interface, which tells that the object can be serialized or not."

Java Serialize HashMap Example 3: Serialize HashMap of user-defined object values

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

class Book implements Serializable {
    private String name;
    private Integer price;
    private String edition;

    public Book(String name, String edition, Integer price) {
        this.name = name;
        this.price = price;
        this.edition = edition;
    }

    @Override
    public String toString() {
        return "[ name : " + name + ", edition : " + edition + ", " 
                                + "price : " + price + "]";
    }
}

public class HashMapExample {
    public static void main(String[] args) {
        // Create a HashMap of Book code as Integer Key and Book Object as value
        HashMap<Integer, Book> books = new HashMap<>();
        books.put(101, new Book("Learn Java", "8th", 550));
        books.put(102, new Book("Coding in Python", "5th", 750));
        books.put(103, new Book("Data Structures", "2nd", 400));
        books.put(104, new Book("Introduction to Database", "4th", 500));

        // Serialize HashMap of user-defined object values
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("books-file");
            ObjectOutputStream objectOutputStream 
                = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(books);

            fileOutputStream.close();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialize HashMap of user-defined object values
        try {
            FileInputStream fileInputStream = new FileInputStream("books-file");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            HashMap<Integer, Book> deserializedBooks 
                = (HashMap<Integer, Book>) objectInputStream.readObject();
            deserializedBooks.entrySet().forEach(entry -> {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            });

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
101 = [ name : Learn Java, edition : 8th, price : 550]
102 = [ name : Coding in Python, edition : 5th, price : 750]
103 = [ name : Data Structures, edition : 2nd, price : 400]
104 = [ name : Introduction to Database, edition : 4th, price : 500]

Importance of "transient" keyword in Serialization

In the above program, all the fields of Book class are serialized and stored in the file. If we do not want to serialize any field then we can make that field transient. The transient keyword is used to make any field not to be serialized into the stream of bytes at the time of serialization.
Syntax
transient int price;

Java Serialize ArrayList Example 4: Serialize HashMap of user-defined object valuess with a transient fields

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

class Book implements Serializable {
    private String name;
    private Integer price;
    transient private String edition;

    public Book(String name, String edition, Integer price) {
        this.name = name;
        this.price = price;
        this.edition = edition;
    }

    @Override
    public String toString() {
        return "[ name : " + name + ", edition : " + edition + ", " 
                                + "price : " + price + "]";
    }
}

public class HashMapExample {
    public static void main(String[] args) {
        // Create a HashMap of Book code as Integer Key and Book Object as value
        HashMap<Integer, Book> books = new HashMap<>();
        books.put(101, new Book("Learn Java", "8th", 550));
        books.put(102, new Book("Coding in Python", "5th", 750));
        books.put(103, new Book("Data Structures", "2nd", 400));
        books.put(104, new Book("Introduction to Database", "4th", 500));

        // Serialize HashMap of user-defined object values
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("books-file");
            ObjectOutputStream objectOutputStream 
                = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(books);

            fileOutputStream.close();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialize HashMap of user-defined object values
        try {
            FileInputStream fileInputStream = new FileInputStream("books-file");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            HashMap<Integer, Book> deserializedBooks 
                = (HashMap<Integer, Book>) objectInputStream.readObject();
            deserializedBooks.entrySet().forEach(entry -> {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            });

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
101 = [ name : Learn Java, edition : null, price : 550]
102 = [ name : Coding in Python, edition : null, price : 750]
103 = [ name : Data Structures, edition : null, price : 400]
104 = [ name : Introduction to Database, edition : null, price : 500]
As we can see from the output, the edition field remains null after the deserialization. Because at the time of serialization of HashMap, the edition field could not be serialized into the file as it is declared as transient.

Related Article


Comments