How to check if a HashMap is empty or not?

This is  a program to check if HashMap is empty or not. isEmpty() method of HashMap class is used to perform this check.

Syntax :

public boolean isEmpty() : According to Oracle docs, this method returns true if the map contains no key-value mappings.

Program for How to Check if a HashMap is Empty or Not 

import java.util.*;

 public class HashMapEmptyExample {
    public static void main(String args[]) {
        
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Checking whether HashMap is empty or not
    /* isEmpty() method signature and description -
     * public boolean isEmpty(): Returns true if this map 
     * contains no key-value mappings.
     */
    System.out.println("Is HashMap Empty? "+hashmap.isEmpty());
    
    
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Apple");
    hashmap.put(22,"Banana");
    hashmap.put(33,"Mango");
    hashmap.put(44,"Pear");
    hashmap.put(55,"PineApple");
     // Checking again whether HashMap is Empty or not
    System.out.println("Is HashMap Empty? "+hashmap.isEmpty());
 
    }
}


Output

Is HashMap Empty? true
Is HashMap Empty? false



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry