HashMap Tutorial In Java with Example

HashMap is a type of Collection, that stores our data in a pair such that each element has a key associated with it. The pair of key and value is often known as Entry and these entries can have only unique keys.

HashMap is a class that implements Map Interface and Extends AbstractMap class which provides the basic structural implementation of Map Interface which minimizes the efforts that are required to implement the Map interface directly in our HashMap Class.

It is generally denoted as HashMap <key, value> or HashMap <K,V>.

Important Note: HashMap allows null key and null value in it, but with a restriction that there can be only one null key and multiple null values.


Hierarchy of HashMap Class

HashMap Class extends AbstractMap Class and that Implements Map Interface as shown in  figure 1.

hierarchy of hashmap


 Examples of HashMap class

Let us discuss Hash map with the help of following programs.

In this program we have created object of HashMap Class, added key value pairs using put method, and displayed it using getKey and getValue methods , as shown below

import java.util.*;

public class HashMapDemoClass{

public static void main(String args[]){

//Step 1: Defing object of HashMap Class

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

//Step 2: Adding Key Value pair

HashMap.put(1001,"India");

HashMap.put(1002,"Canada");

HashMap.put(1003,"Australia");

//Step 3: Displaying key value pairs using for loop

for(Map.Entry map  :  HashMap.entrySet() )

{

//Step 4: Using getKey and getValue methods to retrieve key and corresponding value

System.out.println(map.getKey()+" "+map.getValue());

}
}
}

Output

1001 India

1002 Canada

1003 Australia

Description:

  • In Step 1, we have created an object of HashMap collection, As we have already discussed HashMap has key value pair, so obviously we have to define the type of key and value, We have defined Key of Integer type, and Value of String type.
  • In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
  • In Step 3, we have used for each loop of following syntax to retrieve the values from the HashMap object

for(Map.Entry map  :  HashMap.entrySet())

In this for loop we have used method entrySet(), which returns a Set view of the mappings contained in the HashMap object and the Map.Entry is an Interface that enables you to work with a map entry easily by which key-value pairs are retrieved one by one, and are displayed in next step.

  • In Step 4 we have used two methods , as shown

System.out.println(map.getKey()+” “+map.getValue());

First is  getKey() , which as name suggest retrieves the key and secondly getValue() method that retrieves the value corresponding to the given key.


Adding Entry with Duplicate Key in HashMap

HashMap does not allow Entry with duplicate key, it overlaps old value with new one. Below program helps you understand this.

In this program we have created object of HashMap Class and added key value pairs, one with duplicate key, as shown in the following program

import java.util.*;
public class HashMapDemoClass{
public static void main(String args[]){

//Step 1: Defining object of HashMap Class
HashMap<Integer,String> HashMap=new HashMap<Integer,String>();

//Step 2: Adding Key Value pair

HashMap.put(1001,"India");

HashMap.put(1002,"Canada");

HashMap.put(1003,"Australia");

//Step 3: Displaying key value pairs using for loop

for(Map.Entry map  :  HashMap.entrySet() )

{

//Step 4: Using getKey and getValue methods to retrieve key and corresponding value

System.out.println(map.getKey()+" "+map.getValue());

}

//Step 5: Adding element with duplicate key

HashMap.put(1003,"Nepal");

 
//Step 6: Displaying Elemnets

System.out.println("Entries after adding element with Duplicate Key");

for(Map.Entry map  :  HashMap.entrySet() )

{

System.out.println(map.getKey()+" "+map.getValue());
}
}
}

Output:

1001 India

1002 Canada

1003 Australia

Entries after adding element with Duplicate Key

1001 India

1002 Canada

1003 Nepal

Conclusion: From output it is clear that HashMap does not allow Entry with duplicate key, it overlaps old value with new one, as shown in the output.

Description of Program:

  • In Step 1, we have created an object of HashMap collection
  • In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
  • In Step 3, we have used for each loop to retrieve the values from the HashMap object
  • In Step 4 we have displayed entries , with getkey() and getvalue()  methods that are discussed above
  • In Step 5, we have added an entry with duplicate key
  • In Step 6, we have again displayed all the entries

Adding Entry with Duplicate Value in HashMap

HashMap allows Entry with duplicate value but having unique key.

In this program we have created object of HashMap Class and added key value pairs, one with duplicate value, as shown in the following program

import java.util.*;
public class HashMapDemoClass{
public static void main(String args[]){

//Step 1: Defing object of HashMap Class

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

//Step 2: Adding Key Value pair

HashMap.put(1001,"India");

HashMap.put(1002,"Canada");

HashMap.put(1003,"Australia");

//Step 3: Displaying key value pairs using for loop

for(Map.Entry map  :  HashMap.entrySet() )

{

//Step 4: Using getKey and getValue methods to retrieve key and corresponding value

System.out.println(map.getKey()+" "+map.getValue());

}

//Step 5: Adding element with duplicate value

HashMap.put(1004,"India");

//Step 6: Displaying Elemnets

System.out.println("Entries after adding element with Duplicate Value");

for(Map.Entry map  :  HashMap.entrySet() )

{

System.out.println(map.getKey()+" "+map.getValue());

}

}

}

Output:

1001 India

1002 Canada

1003 Australia

Entries after adding element with Duplicate Value

1001 India

1002 Canada

1003 Australia

1004 India

Conclusion: From output it is clear that HashMap allows Entry with duplicate value.

Description:

  • In Step 1, we have created an object of HashMap collection
  • In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1.
  • In Step 3, we have used for each loop to retrieve the values from the HashMap object
  • In Step 4 we have displayed entries , with getkey() and getvalue() methods that are discussed above
  • In Step 5, we have added an entry with duplicate value
  • In Step 6, we have again displayed all the entries

HashMap Methods in JAVA:

HashMap is a class that implements Map Interface and Extends AbstractMap class.  It is generally denoted as HashMap <key, value> or HashMap <K,V>.

Let us discuss HashMap methods one by one with Examples in Java.

1. Object put(Object key, Object value):

This method adds the key value pair to the HashMap object, as shown in the following program:

import java.util.*;

public class HashMapDemoClass 
{

  public static void main(String args[]) {

// create a hashmap

  HashMap hashmapobj = new HashMap();

// using Object put(Object key, Object value) method

  hashmapobj.put(1001, "I");

  hashmapobj.put(1002, "Love");

  hashmapobj.put(1003, "Java");

//printing the hashmap

  System.out.println(" All the key value pairs " + hashmapobj);

 }

}

Output:

All the key value pairs {1001=I, 1002=Love, 1003=Java}

2. int size():

This method returns the size of the HashMap as shown in the following program:

package com.test;
import java.util.*;

public class HashMapDemoClass 
{

  public static void main(String args[]) {

 // create a hashmap

  HashMap hashmapobj = new HashMap();

  hashmapobj.put(1001, "I");

  hashmapobj.put(1002, "Love");

  hashmapobj.put(1003, "Java");

  //using size() method

  System.out.println(" Size of hashmap is " + hashmapobj.size());

 }

}

Output:

Size of hashmap is 3

3. void clear():

This method clears all the key value pairs in the HashMap, as shown in the following program:

import java.util.*;

public class HashMapDemoClass 
{

   public static void main(String args[]) {

  // create a hashmap

   HashMap hashmapobj = new HashMap();

   hashmapobj.put(1001, "I");

   hashmapobj.put(1002, "Love");

   hashmapobj.put(1003, "Java");

  //using size() method

   System.out.println(" Size of hashmap is " + hashmapobj.size());

   //using clear() method

   hashmapobj.clear();

  //using size() method  after clearing the hashmap

   System.out.println(" Size of hashmap after clearing is " + hashmapobj.size());

 }

}

Output:

Size of hashmap is 3

Size of hashmap after clearing is 0

Read all HashMap Methods in JAVA


Important Points About HashMap

  • For using HashMap you must need to import util.HashMap or its super class .
  • HashMap only stores values with unique keys, that is duplicate keys are not allowed.
  • HashMap do not maintains order, which means it does not return the key value pair in the order in which they have been added.
  • It does not do any kind of sorting to the stored keys and values.
  • HashMap allows null key and null value in it,but with a restriction that there can be only one null key and multiple null values.
  • HashMap is very much similar to HashTable, but with few differences, firstly HashMap is not thread safe, where as HashTable is thread safe. Secondly, HashMap is unsynchronized, where as HashTable is, So performance of HashMap is better than HashTable.
  • To add thread safety or we can say to make HashMap synchronized we have class ConcurrentHashMap, which makes it threadsafe and synchronized.

HashMap Quick Revision Points

  • Data is stores in key value pair.
  • Duplicate keys are not allowed.
  • No insertion order is maintained.
  • It can have only one null key and multiple null values.
  • It is not thread safe.
  • It is unsynchronized.
  • It performs better as compared to HashTable.

Leave a Reply

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