Java HashMap isEmpty() Example

The isEmpty() method of java.util.HashMap class will tests if the HashMap has any elements or not.

Signature

public boolean isEmpty() 

This method checks if the HashMap has any elements in it or not, returns true if and only if the HashMap has no components,else it will return false.

Example

The following example shows the usage of java.util.HashMap.isEmpty() method.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class IsEmptyMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String>  hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        //Check if hashMap1 is empty or not 
        System.out.println("Is \"hashMap1\" empty : "+hashMap1.isEmpty());
} }

Output

Is "hashMap1" empty : false

Leave a Reply

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