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

HashMap in Java With Examples

By Chaitanya Singh | Filed Under: java

HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. HashMap in java, is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. It does not sort the stored keys and values. You must need to import java.util.HashMap or its super class in order to use the HashMap class and methods.

HashMap

Let’s discuss HashMap in detail.

  • In key-value pairs, the key must be unique.
  • It is non-synchronized. However you can make it synchronized.
  • Doesn’t maintain insertion order.
  • Doesn’t sort elements
  • It allows null keys and values. However only one null key is allowed. Multiple null values are allowed.

HashMap class hierarchy

HashMap in Java

How to declare HashMap in Java?

HashMap<K, V> hmap = new HashMap<K, V>();

K: It represents the type of the key in a key-value pair.
V: It represents the type of a value in a key-value pair.

For example: A HashMap that has integer keys and string values can be declared like this:

HashMap<Integer, String> hmap = new HashMap<Integer, String>();

HashMap in Java Examples

1. Adding elements to HashMap

You can use the put() method of the HashMap class to add new key-value pairs to the HashMap. To iterate the HashMap, we are using entrySet() method. This method returns an equivalent Set. This is to pass the key-value pairs to the Map.Entry, which contains the methods getKey() and getValue() that we can use to print key-value pairs of HashMap. HashMap elements are traversed using for loop and key-value pairs are printed.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    HashMap<Integer,String> hMap=new HashMap<>();
    hMap.put(101,"Cricket");
    hMap.put(105,"Hockey");
    hMap.put(111,"Basketball");

    System.out.println("HashMap elements: ");
    for(Map.Entry mEntry : hMap.entrySet()){
      System.out.print("key: "+ mEntry.getKey() + " & Value: ");
      System.out.println(mEntry.getValue());
    }
  }
}

Output:
HashMap in Java Example output

2. Checking duplicate key insertion in HashMap

Here, we are trying to add element with a duplicate key. The new element (111,”Karate”) has the key value 111, which is already present in the HashMap. Instead of adding this new element, HashMap updated the value of already existing element with key “111”.

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    HashMap<Integer,String> hMap=new HashMap<>();
    hMap.put(101,"Cricket");
    hMap.put(105,"Hockey");
    hMap.put(111,"Basketball");
    hMap.put(111,"Karate"); //adding element with duplicate key

    System.out.println("HashMap elements: ");
    for(Map.Entry mEntry : hMap.entrySet()){
      System.out.print("key: "+ mEntry.getKey() + " & Value: ");
      System.out.println(mEntry.getValue());
    }
  }
}

Output:
HashMap duplicate key example

3. HashMap remove() method Example

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    HashMap<Integer,String> hMap=new HashMap<>();
    hMap.put(101,"Cricket");
    hMap.put(105,"Hockey");
    hMap.put(111,"Basketball");

    //this will remove the key-value pair where
    //the value of the key is 101
    hMap.remove(101);

    System.out.println("HashMap elements: ");
    for(Map.Entry mEntry : hMap.entrySet()){
      System.out.print("key: "+ mEntry.getKey() + " & Value: ");
      System.out.println(mEntry.getValue());
    }
  }
}

Output:

HashMap elements: 
key: 105 & Value: Hockey
key: 111 & Value: Basketball

4. HashMap replace() method Example

import java.util.*;
public class JavaExample{
  public static void main(String args[]){
    HashMap<Integer,String> hMap=new HashMap<>();
    hMap.put(101,"Cricket");
    hMap.put(105,"Hockey");
    hMap.put(111,"Basketball");

    //this will update the value of key-value pair
    //where the key is 105
    hMap.replace(105, "Kickboxing");

    System.out.println("HashMap elements: ");
    for(Map.Entry mEntry : hMap.entrySet()){
      System.out.print("key: "+ mEntry.getKey() + " & Value: ");
      System.out.println(mEntry.getValue());
    }
  }
}

Output:

HashMap elements: 
key: 101 & Value: Cricket
key: 105 & Value: Kickboxing
key: 111 & Value: Basketball

Internal working of HashMap in Java

HashMap internally uses a technique called hashing to generate index for keys. This indexing allows faster searching of record. This allows faster response time for operations such as search, update, delete etc.

When we call the HashMap put() method as shown in the following statement. It calculates the hash code of the key (101 in this case) using hash function. This hash code is calculated using the hashing technique. An index is assigned to this hash code. This index uniquely identifies this key-value pair.

HashMap<Integer,String> hMap=new HashMap<>();
hMap.put(101,"Cricket");

When a duplicate key is inserted into the HashMap, Hash Collision happens. HashMap handles this by updating the old value with the new value.

HashMap Class Methods

Here is the list of methods available in HashMap class. I have also covered examples using these methods at the end of this post.

  1. void clear(): It removes all the key and value pairs from the specified Map.
  2. Object clone(): It returns a copy of all the mappings of a map and used for cloning them into another map.
  3. boolean containsKey(Object key): It is a boolean function which returns true or false based on whether the specified key is found in the map.
  4. boolean containsValue(Object Value): Similar to containsKey() method, however it looks for the specified value instead of key.
  5. Value get(Object key): It returns the value for the specified key.
  6. boolean isEmpty(): It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.
  7. Set keySet(): It returns the Set of the keys fetched from the map.
  8. value put(Key k, Value v): Inserts key value mapping into the map. Used in the above example.
  9. int size(): Returns the size of the map – Number of key-value mappings.
  10. Collection values(): It returns a collection of values of map.
  11. Value remove(Object key): It removes the key-value pair for the specified key. Used in the above example.
  12. void putAll(Map m): Copies all the elements of a map to the another specified map.

HashMap Example to demonstrate various methods

In this example we have demonstrated almost all the important methods of HashMap class.

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {

   public static void main(String args[]) {

      /* This is how to declare HashMap */
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");

      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);

      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }

   }
}

Output:

key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya

HashMap Tutorials

Here is the list of tutorials published on HashMap class. Happy Learning:)

HashMap Basics

  1. How to iterate HashMap
  2. Sort HashMap by Keys and values
  3. Get Size of HashMap
  4. Remove Key-value mapping from HashMap
  5. Remove all mapping from HashMap
  6. How to check if HashMap is empty or not?

Get/Search

  1. Check if particular key exists in HashMap
  2. Check if particular value exists in HashMap

Serialize/Synchronize

  1. Serialize HashMap
  2. Synchronize HashMap

Differences

  1. HashMap vs ArrayList
  2. HashMap vs Hashtable
  3. HashSet vs HashMap

Other Tutorials

  1. HashMap Iterator example
  2. Copy one HashMap to another
  3. Get value from HashMap using Key
  4. Get Set view of keys from HashMap
  5. Clone a HashMap
❮ TreeSetTreeMap ❯

Comments

  1. Raju says

    March 31, 2014 at 4:27 PM

    Mind Blowing……

    Do something so that your website can have more views………this is very much useful for beginners……………….

    Reply
    • Chaitanya Singh says

      April 6, 2014 at 3:33 PM

      Thanks for your kind words Raju :)

      Reply
      • piyush shukla says

        July 26, 2014 at 3:44 PM

        very good explanation…

        Reply
  2. May says

    July 17, 2014 at 2:59 PM

    Hi Chaitanya,
    This tutorial is really very understandable.
    I have been trying to learn Java from a long time but am not really able to get to undertsand the concepts well enough to use them wherever needed. Can you please suggest me how to learn so I can use the concepts in my day today job.

    Reply
  3. Farhan Ali says

    October 25, 2015 at 6:51 PM

    Hello Sir,
    I don’t understand why have you used set for iterating while it can be easily done with keySet();.

    Reply
    • sunny says

      June 14, 2016 at 6:12 AM

      keyset() also return SET.
      but if you use KeySet() – it will just return all keys in one go but if you want to traverse each key and do some operation you required something else and the same was explained by Chaitanya..

      Hope this help!

      Reply
  4. Line says

    May 18, 2016 at 3:24 PM

    Why do I get NullPointerException?

    Reply
    • Tamil selvan s says

      November 22, 2016 at 4:17 AM

      There may be no objects available at that area or space in which you are accessing.

      For example we can take an array

      int a[] = new int[5];
      here the available values are a[0],a[1],a[2],a[3],a[4] if u try to fix values for a[5] then you will get nullpointerexception!!!!!!!

      Reply
  5. Andrew says

    April 30, 2017 at 5:26 PM

    I want to know why the order of the output is not the same as we input them. Would you mind email me your reply? Thanks!

    Reply
    • Max Bradley says

      August 17, 2017 at 11:20 AM

      Hi Andrew,

      I was wondering the same, I think it is just a property of HashMaps that there is no ordering. When you add items to them you are not adding after any existing entries, you are just added to a pool of key-value pairs.

      Reply
      • Karthi says

        August 16, 2018 at 1:25 PM

        Read these lines again please

        It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the Hash Map. It does not sort the stored keys and Values.

        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 – 2022 BeginnersBook . Privacy Policy . Sitemap