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;
map
, an instance of the Java HashMap, can call the isEmpty()
function, as illustrated below:
The isEmpty()
function accepts no parameters and returns a boolean value of True
or False
.
The following example demonstrates how to use the isEmpty()
function with a Java HashMap.
results
and indicates in line 7 that the first element of a pair is a string and the second element is an integer.results
is empty and displays the result.results
HashMap through the put()
method and displays the HashMap.results
is 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