java.util.HashMap isEmpty()

Description :

On this document we will be showing a java example on how to use the isEmpty() method of HashMap Class. Basically this method just returns true if the HashMap object contains zero key-value combinations. This method might be useful in situation wherein we have to test if the map is empty or not and do business logic depending on the result. Important notes for size method:

  • specified by isEmpty in interface Map<K,V>
  • overrides isEmpty in class AbstractMap<K,V>

Method Syntax :

public boolean isEmpty()

Parameter Input :


DataType Parameter Description


Method Returns :

The size method returns a boolean value depending on the result:

  • true if the map contains no key-value pair
  • false if the map object contains at least one key-value pairs

Compatibility Version :

Requires Java 1.2 and up

Exception :


Java Code Example :

This java example source code demonstrates the use of isEmpty() method of HashMap class. From the example below, basically we just assign values to our HashMap at the start of the code. After which we then check if it is not empty. If the map is found to be not empty, we print out the contents. This is a good example in how to loop through the contents of HashMap. If you want to learn more on the usage of each of the methods that we have used here, please go through with each of the examples and documentation that we have provided located at the left navigation pane of this page.


import java.util.HashMap;
import java.util.Scanner;

 * This example source code demonstrates the use of  
 * isEmpty() method of HashMap class

public class HashMapIsEmptyExample {

	public static void main(String[] args) throws InterruptedException {

		// declare the hashmap
		HashMap<String, String> mapStudent = new HashMap<>();
		// put contents of our HashMap
		mapStudent.put("12487912", "Shyra Travis");
		mapStudent.put("45129987", "Sharon Wallace");
		// check if the HashMap is empty or not
		if (!mapStudent.isEmpty()) {
			// printing the key value pairs available
			// if the hashmap is not empty
			for (String s : mapStudent.keySet()) {
				System.out.println("Student with id # " + s + " is "
						+ mapStudent.get(s));


Sample Output :

Running the above java example of the usage of HashMap isEmpty() method will give the following output:

HashHamp isEmpty() method example

HashHamp isEmpty() method example Output

Similar Method :

  • N/A

Suggested Reading List :

References :