Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

How to use the HashMap isEmpty() function in Java

Ayesha Naeem

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 results and 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 results is empty and displays the result.
  • It then populates the results HashMap through the put() method and displays the HashMap.
  • The program checks if results is empty again and displays the results.
import java.util.HashMap;

class ExampleHashMap {
    public static void main(String[] args) {

        // create a new hashmap
        HashMap<String, Integer> results = new HashMap<>();

        System.out.println("A HashMap for mapping marks to students");

        // check if the results hashmap is empty
        boolean 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 hashmap

        results.put("Ali", 89);

        results.put("Ahmed", 95);

        results.put("Sana", 70);

        results.put("Amna", 100);

        //display the hashmap

        System.out.println("Updated HashMap: " + results);

        //check if it is empty again
        empty = results.isEmpty(); 
        if (empty)
        {
            System.out.println("The Results Hashmap is empty");
        }
        else
        {
            System.out.println("The Results Hashmap is not empty");
        }
    }
}

RELATED TAGS

java

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring