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:
// Java Program to serialize and deserialize a TreeMap
import java.io.*;
import java.util.TreeMap;
public class TreeMapSerializationExample
{
public static void main(String[] args)
{
// Create a TreeMap
TreeMap<String, Integer> studentScores = new TreeMap<>();
studentScores.put("Rahul", 85);
studentScores.put("Sushma", 98);
studentScores.put("Kanna", 99);
// Serialize the TreeMap
serializeTreeMap(studentScores, "treeMapSerialized.ser");
// Deserialize the TreeMap
TreeMap<String, Integer> deserializedTreeMap = deserializeTreeMap("treeMapSerialized.ser");
// Display the deserialized TreeMap
System.out.println("Deserialized TreeMap: " + deserializedTreeMap);
}
// Serialize the TreeMap
private static void serializeTreeMap(TreeMap<String, Integer> treeMap, String fileName)
{
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)))
{
oos.writeObject(treeMap);
System.out.println("TreeMap serialized successfully.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Deserialize the TreeMap
private static TreeMap<String, Integer> deserializeTreeMap(String fileName)
{
TreeMap<String, Integer> deserializedTreeMap = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName)))
{
deserializedTreeMap = (TreeMap<String, Integer>) ois.readObject();
System.out.println("TreeMap deserialized successfully.");
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
return deserializedTreeMap;
}
}
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
studentScoreswith 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.