Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Serialize HashMap in Java with Example

In the last tutorial we have learnt about how to synchronize Hashmap in java. In this tutorial we will learn about the serialize behavior of HashMap. The  important point to note is that HashMap class is serialized by default.It means HashMap class  does not need to implement Serializable interface in order to make it eligible for Serialization.


Serialization of HashMap : 

In the below example we are storing the HashMap content  in a hashmap.ser  serialized file. Once you run the below code it would produce a hashmap.ser file.The hashmap.ser file is then used in the de-serialization of HashMap.


import java.util.*;
import java.io.*;
public class HashMapSerializeExample { public static void main(String args[]) { // Creating a HashMap of Integer keys and String values HashMapInteger, String> hashmap = new HashMapInteger, String>(); hashmap.put(1, "Value1"); hashmap.put(2, "Value2"); hashmap.put(3, "Value3"); hashmap.put(4, "Value4"); hashmap.put(5, "Value5"); try { FileOutputStream fos = new FileOutputStream("hashmap.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(hmap); oos.close(); fos.close(); System.out.printf("Serialized HashMap data is saved in hashmap.ser"); }catch(IOException ioe) { ioe.printStackTrace(); } }}


Output
Serialized HashMap data is saved in hashmap.ser

Deserialization of HashMap : In the deserialization we are reproducing the HashMap object and its content from a serialized file which we have by running the above code.


import java.util.*;

public class HashMapDeserializeExample {
public static void main(String args[]) {

HashMapInteger, String> map = null;
try
{
FileInputStream fis = new FileInputStream("hashmap.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
map = (HashMap) ois.readObject();
ois.close();
fis.close();
}catch(IOException ioe)
{
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized HashMap");
// Display content using Iterator
Set set = map.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key: "+ mentry.getKey() + " & Value: ");
System.out.println(mentry.getValue());
}
}
}


Output
Deserialized HashMap
key: 1 & Value: Value1
key: 2 & Value: Value2
key: 3 & Value: Value3
key: 4 & Value: Value4
key: 5 & Value: Value5


This post first appeared on Java Hungry, please read the originial post: here

Share the post

How to Serialize HashMap in Java with Example

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×