Open In App

What are the Considerations for Serializing and Deserializing a TreeMap, including Custom Object Serialization in Java?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Serialization is the process of converting the object into a stream of bytes to store the persistently or transmit through the network. Deserialization is the reverse process of converting the stream of bytes back into the object. We can implement the process of serialization and deserialization using TreeMap of Java.

Step-by-Step Implementation

  • Create a Java class named TreeMapSerialization and add the main method to it.
  • Create the CustomObject class that can be implemented in the Serializable interface with id name variables.
  • Create the instance of the treeMap using the TreeMap data structure.
  • Using the put() method add the values into the treeMap.
  • Now serialize the treeMap using FileOutputStream and ObjectOutputStream and once serialized the treeMap prints the success statement.
  • Again, deserialize the treeMap using readObject() method.
  • Print the deserialized file.

Program to Serialize and Deserialize a TreeMap including Custom Object in Java

Below is the Program to Serialize and Deserialize a TreeMap including a Custom Object:

Java




// Java Program to Serialize and Deserialize
// A TreeMap using Custom Object
import java.io.*;
import java.util.*;
  
// Custom class for non-serializable objects
class CustomObject implements Serializable
{
    private int id;
    private String name;
  
    public CustomObject(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
  
    // Getters and setters
    public int getId()
    {
        return id;
    }
  
    public String getName()
    {
        return name;
    }
  
    // Overridden toString() method to print object details
    @Override
    public String toString()
    {
        return "CustomObject{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
  
public class TreeMapSerializationExample
{
    public static void main(String[] args)
    {
        // Create a TreeMap with custom object as value
        TreeMap<String, CustomObject> treeMap = new TreeMap<>();
        treeMap.put("One", new CustomObject(1, "Object One"));
        treeMap.put("Two", new CustomObject(2, "Object Two"));
        treeMap.put("Three", new CustomObject(3, "Object Three"));
  
        // Serialize the TreeMap
        try {
            FileOutputStream fileOut = new FileOutputStream("treeMap.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(treeMap);
            out.close();
            fileOut.close();
            System.out.println("TreeMap serialized successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
  
        // Deserialize the TreeMap
        try {
            FileInputStream fileIn = new FileInputStream("treeMap.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            TreeMap<String, CustomObject> deserializedTreeMap = (TreeMap<String, CustomObject>) in.readObject();
            in.close();
            fileIn.close();
            System.out.println("Deserialized TreeMap: ");
            // Iterate through the deserialized TreeMap and print each key-value pair
            for (Map.Entry<String, CustomObject> entry : deserializedTreeMap.entrySet()) {
                System.out.println(entry.getKey() + " -> " + entry.getValue());
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


Output

TreeMap serialized successfully.
Deserialized TreeMap: 
One -> CustomObject{id=1, name='Object One'}
Three -> CustomObject{id=3, name='Object Three'}
Two -> CustomObject{id=2, name='Object Two'}


Explanation of the above Program:

In the above example of the serializing and deserializing the TreeMap including custom object.

  • In this example, we have created the TreeMap, and it can store the key-pairs where keys are type of String and values are type of Integer then some values are added into the treeMap.
  • Now, we can serialize the treeMap then it saved as treeMap.ser using objectOutputStream.
  • In serialization process, FileOutputStream is the responsible for the writing bytes to the file and objectOutputStream is the responsible for serializing the treeMap object.
  • We can deserialize the treeMap.ser serialize fie is read using FileInputStream and ObjectInputStream can reads the serialized TreeMap object from the file and deserialize it.
  • Finally, the deserialized TreeMap can be printed as result output.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads