HashMap isEmpty() Method in Java

Published by user on

The isEmpty() method of HashMap checks if the map contains any key/value pairs. It returns true if the map does not contain any entries.
More formally, it returns true if the size of the HashMap is equal to zero. If the size of the HashMap is greater than zero then the isEmpty() method returns false.

Method Signature

public boolean isEmpty()

Parameters

It does not accept any parameters.

Returns

boolean i.e true when HashMap is empty, otherwise false.

Program

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

// This program shows
// how to use isEmpty() method
// to check if the HashMap is empty or not
public class HashMapIsEmpty {

	public static void main(String[] args) {

		// Create a HashMap
		Map<Integer, String> map = new HashMap<>();
		// Put entries into the HashMap
		map.put(101, "John");
		map.put(102, "Adam");
		map.put(103, "Ricky");
		map.put(104, "Chris");

		// Print the elements
		System.out.println("HashMap elements : " + map);

		// At this point, HashMap has entries in it
		// Hence isEmpty() returns false
		System.out.println("Is HashMap empty? : " + map.isEmpty());

		// Clear the HashMap
		map.clear();

		// HashMap doesn't have entries now
		System.out.println("HashMap elements after clear : " + map);
		// isEmpty() returns true
		System.out.println("Is HashMap empty? : " + map.isEmpty());
	}
}

Output

HashMap elements : {101=John, 102=Adam, 103=Ricky, 104=Chris}
Is HashMap empty? : false
HashMap elements after clear : {}
Is HashMap empty? : true

Explanation

  1. Create an instance of HashMap
  2. Add entries into it
  3. Call isEmpty() to check if the entries are present. Here isEmpty() returns false
  4. Clear the HashMap using the clear() method
  5. At this point, the size of HashMap is equal to zero. Therefore, call to isEmpty() returns true
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

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