beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to serialize HashMap in java

By Chaitanya Singh | Filed Under: Java Collections

HashMap class is serialized by default which means we need not to implement Serializable interface in order to make it eligible for Serialization. In this tutorial we will learn How to write HashMap object and it’s content into a file and How to read the HashMap object from the file. Before I share the complete code for this let me give a brief info about Serialization and De-serialization.

Serialization: It is a process of writing an Object into file along with its attributes and content. It internally converts the object in stream of bytes.

De-Serialization: It is a process of reading the Object and it’s properties from a file along with the Object’s content.

Example:

Serialization of HashMap: In the below class 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. This file would be used in the next class for de-serialization.

package beginnersbook.com;
import java.io.*;
import java.util.HashMap;
public class Details
{
      public static void main(String [] args)
      {
           HashMap<Integer, String> hmap = new HashMap<Integer, String>();
           //Adding elements to HashMap
           hmap.put(11, "AB");
           hmap.put(2, "CD");
           hmap.put(33, "EF");
           hmap.put(9, "GH");
           hmap.put(3, "IJ");
           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

De-Serialization: Here we are reproducing the HashMap object and it’s content from a serialized file which we have created by running the above code.

package beginnersbook.com;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Student
{
   public static void main(String [] args)
   {
      HashMap<Integer, 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: 9 & Value: GH
key: 2 & Value: CD
key: 11 & Value: AB
key: 33 & Value: EF
key: 3 & Value: IJ

References:

  • HashMap Documentation
  • Serializable javadoc
  • ObjectOutputStream javadoc
  • ObjectInputStream Documentataion
  • FileInputStream
  • FileOutputStream

Enjoyed this post? Try these related posts

  1. Java – Add element at specific index in LinkedList example
  2. Java ArrayList of Object Sort Example (Comparable And Comparator)
  3. Java – Get first and last elements from LinkedList example
  4. Java ArrayList isEmpty() Method example
  5. Remove mapping from Hashtable example – Java
  6. How to sort ArrayList in Java

Comments

  1. Reddy says

    August 9, 2014 at 8:12 AM

    Hi,
    Your code is very good understandable

    If you provide more detailed description it will help lot.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap