How to use the HashMap isEmpty() function in Java
An instance of the Java HashMap calls the isEmpty() function, which returns True if that HashMap is empty, and False if it is not empty.
To use the isEmpty() function with HashMaps, the program needs to import the java.util.HashMap module:
import java.util.HashMap;
Prototype
map, an instance of the Java HashMap, can call the isEmpty() function, as illustrated below:
Parameters and return type
The isEmpty() function accepts no parameters and returns a boolean value of True or False.
Example
The following example demonstrates how to use the isEmpty() function with a Java HashMap.
- The program below creates a HashMap
resultsand indicates in line 7 that the first element of a pair is a string and the second element is an integer. - The program then checks if
resultsis empty and displays the result. - It then populates the
resultsHashMap through theput()method and displays the HashMap. - The program checks if
resultsis empty again and displays the results.
import java.util.HashMap;class ExampleHashMap {public static void main(String[] args) {// create a new hashmapHashMap<String, Integer> results = new HashMap<>();System.out.println("A HashMap for mapping marks to students");// check if the results hashmap is emptyboolean empty = results.isEmpty();if (empty){System.out.println("The Results Hashmap is empty");}else{System.out.println("The Results Hashmap is not empty");}// add elements to the hashmapresults.put("Ali", 89);results.put("Ahmed", 95);results.put("Sana", 70);results.put("Amna", 100);//display the hashmapSystem.out.println("Updated HashMap: " + results);//check if it is empty againempty = results.isEmpty();if (empty){System.out.println("The Results Hashmap is empty");}else{System.out.println("The Results Hashmap is not empty");}}}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved