Skip to main content

Serialize HashSet in Java

How to serialize hashset in Java

In this article, we are going to learn how to serialize HashSet in Java. Also, we will see how to deserialize HashSet in Java. To serialize or deserialize, the class must implement the java.io.Serializable interface. In our case, we can serialize HashSet as HashSet class implements Serializable Interface, See the hierarchy of HashSet.
"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."


How to serialize HashSet of strings?

Let's start with a very basic example to serialize HashSet of string objects. We can use the writeObject() method of ObjectOutputStream to serialize HashSet in Java.

Java Serialize HashSet Example 1: Serialize HashSet of strings

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Arrays;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> languageSet = new HashSet<>(
            Arrays.asList("Java", "C++", "NodeJS", "JavaScript", "Python"));
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("data");
            ObjectOutputStream objectOutputStream 
                  = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(languageSet);

            objectOutputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In the above example, we serialize HashSet of different programming languages using the writeObject() method. Run this program and see into your file system, a file named with the "data" will be created. Now, learn how to read that file and deserialize the HashSet.

Java Serialize HashSet Example 2: Deserialize HashSet of strings

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

public class HashSetExample {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream = new FileInputStream("data");
            ObjectInputStream objectInputStream 
                = new ObjectInputStream(fileInputStream);

            HashSet<String> hashSet 
                = (HashSet<String>) objectInputStream.readObject();
            System.out.println(hashSet);

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
[Java, C++, NodeJS, JavaScript, Python]

How to serialize HashSet of user-defined objects?

We can also serialize HashSet 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 HashSet of string objects 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 HashSet Example 3: Serialize HashSet of user-defined objects

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.HashSet;

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 HashSetExample {
    public static void main(String[] args) {
        HashSet<Book> bookSet = new HashSet<>();
        bookSet.add(new Book("Learn Java", "8th", 550));
        bookSet.add(new Book("Coding in Python", "5th", 750));
        bookSet.add(new Book("Data Structures", "2nd", 400));
        bookSet.add(new Book("Introduction to Database", "4th", 500));

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

            objectOutputStream.writeObject(bookSet);

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

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

            HashSet<Book> deserializedBookSet
                = (HashSet<Book>) objectInputStream.readObject();
            for (Book book : deserializedBookSet) {
                System.out.println(book);
            }

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
[ name : Learn Java, edition : 8th, price : 550]
[ name : Coding in Python, edition : 5th, price : 750]
[ name : Data Structures, edition : 2nd, price : 400]
[ 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 HashSet Example 4: Serialize HashSet of user-defined objects with few 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.HashSet;

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 HashSetExample {
    public static void main(String[] args) {
        HashSet<Book> bookSet = new HashSet<>();
        bookSet.add(new Book("Learn Java", "8th", 550));
        bookSet.add(new Book("Coding in Python", "5th", 750));
        bookSet.add(new Book("Data Structures", "2nd", 400));
        bookSet.add(new Book("Introduction to Database", "4th", 500));

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

            objectOutputStream.writeObject(bookSet);

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

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

            HashSet<Book> deserializedBookSet
                = (HashSet<Book>) objectInputStream.readObject();
            for (Book book : deserializedBookSet) {
                System.out.println(book);
            }

            fileInputStream.close();
            objectInputStream.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
[ name : Learn Java, edition : null, price : 550]
[ name : Coding in Python, edition : null, price : 750]
[ name : Data Structures, edition : null, price : 400]
[ 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 HashSet, the edition field could not be serialized into the file as it is declared as transient.

Comments