HashMap Example Java Program

Definition

A Hashmap is a Map data structure. Like a list each item that is stored in a hashmap is stored at a particular index. This index is called a hash and it is generated using a hash function. Hash functions accept the object to be stored as an argument and generate a number that is unique to it.

Syntax

HashMap  Variable_name = new HashMap();

HashMap Example Program

import java.util.HashMap;
 
public class HashMapExample {
    public static void main(String a[]){
		HashMap hm = new HashMap();
        hm.put("1","FIRST");
        hm.put("2","SECOND");
        hm.put("3","THIRD");
		hm.put("4",null);
		hm.put(null,"FIFTH");
        System.out.println("hashmap is "+hm);
        System.out.println("Value of 1: "+hm.get("1"));
        System.out.println("Is HashMap empty? "+hm.isEmpty());
        hm.remove("2");
        System.out.println("After removal process, the hashmap is "+hm);
        System.out.println("Size of the HashMap: "+hm.size());
    }
}

Sample Output

Output is:
hashmap is {null=FIFTH, 3=THIRD, 2=SECOND, 1=FIRST, 4=null}
Value of 1: FIRST
Is HashMap empty? false
After removal process, the hashmap is {null=FIFTH, 3=THIRD, 1=FIRST, 4=null}
Size of the HashMap: 4