BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to serialize HashMap in java

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

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

Top Related Articles:

  1. How to loop LinkedList in Java
  2. How to synchronize HashMap in Java with example
  3. How to sort Hashtable in java
  4. Java 8 – Filter null values from a Stream
  5. Constructor Overloading in Java with examples

Tags: Collections, Java-HashMap

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

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 Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap