VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-serialize-and-deserialize-a-treemap-in-java/

⇱ How to Serialize and Deserialize a TreeMap in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Serialize and Deserialize a TreeMap in Java?

Last Updated : 23 Jul, 2025

In Java, serialization is implemented by using the Serializable Interface. The use of the TreeMap class is a simple way to serialize and deserialize the objects. It is a component of the Java Collections framework. For writing and reading objects, we will be using the ObjectOutputStream and ObjectInputStream classes.

In this article, we will be learning how to serialize and deserialize a Java TreeMap in Java.

Program to serialize and deserialize a TreeMap in Java

Step-by-step implementation to Serialize and Deserialize a TreeMap in Java are mentioned below:

  • Implement Serializable Interface: Create a TreeMap class and implement the Serializable interface to serialize its objects.
  • Serialize the TreeMap: Use ObjectOutputStream, to write the class object into a file.
  • Deserialize the TreeMap: Use ObjectInputStream, to read the serialized data and again rebuild the class object.

Below is the implementation to serialize and deserialize a TreeMap:


Output
TreeMap serialized successfully.
TreeMap deserialized successfully.
Deserialized TreeMap: {Kanna=99, Rahul=85, Sushma=98}


Explanation of the Program:

  • In the above program, we have created a TreeMap named studentScores with student names and scores.
  • It then serializes the TreeMap into a file named "treeMapSerialized.ser."
  • After that, it deserializes the TreeMap from the file and displays the deserialized TreeMap.
Comment