Java Collection Framework


Hashmap implements Map interface. 
It extends AbstractMap class.


Declaration of HashMap class

public class HashMap extends AbstractMap implements Map, Cloneable, Serializable

Important points on Hashmap

  • HashMap store data as key, value pairs
  • Each key in HasMap must be unique
  • HashMap can have only one null key but any number of null values.
  • HashMap doesn't maintain order of insertion. It means records are not returned in same order in which they were inserted.
  • To use HashMap, you should import java.util.HashMap or its super class.
  • HashMap is not synchronized.

Create HashMap in java

We can use four different constructors to create HashMap in java as shown below:

  • HashMap myMap = new HashMap();
  • HashMap myMap = new HashMap(int initialCapacity);
  • HashMap myMap = new HashMap(Map m);
  • HashMap myMap = new HashMap(int initialCapacity, float loadFactor);

Simple Example on HashMap

package HashMap;

import java.util.HashMap;

public class SimpleHashMap {

      public static void main(String[] args) {

            HashMap javaRadarMap = new HashMap();

            javaRadarMap.put(1, "Mukesh");
            javaRadarMap.put(2, "Puja");
            javaRadarMap.put(3, "Kavya");
            javaRadarMap.put(4, "Shweta");
            javaRadarMap.put(5, "Rajneesh");
            javaRadarMap.put(6, "Mithilesh");          





{1=Mukesh, 2=Puja, 3=Kavya, 4=Shweta, 5=Rajneesh, 6=Mithilesh}


KeySet in Map

KeySet in java is used to fetch all the keys from the map.

For example, if we write below code snippet in our above program after all the (key, value) has been added then:

//keyset just fetches the key not the value
Iterator i = javaRadarMap.keySet().iterator();          

    while (i.hasNext()){




All the keys are fetched and printed using keyset in java

EntrySet in Map



Iterator i = m.entrySet().iterator();


       Map.Entry entry = (Map.Entry) i.next();

       System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());



Key : 1 Value : Mukesh
Key : 2 Value : Puja
Key : 3 Value : Kavya
Key : 4 Value : Shweta
Key : 5 Value : Rajneesh
Key : 6 Value : Mithilesh





Please Share this page
Views : 92
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!