How to check whether HashMap is empty or not ?

In this article, we will discuss and understand with a program to check whether HashMap is empty or not

In earlier article, we have seen how to check whether HashMap contains particular key/value or Not ? Read below articles for more details with example

  1. How to check whether a particular key is present in HashMap
  2. How to check whether a particular value is present in HashMap

 

To check whether HashMap is empty or not :

Method signature:

public boolean isEmpty();
  • Above method is used to check whether HashMap is empty or not from invoking Map object
  • It can be HashMap or LinkedHashMap or TreeMap
  • Returns true, if Map is empty
  • otherwise return false

HashMapIsEmptyOrNot.java

package in.bench.resources.collection;

import java.util.HashMap;

public class HashMapIsEmptyOrNot {

	public static void main(String[] args) {

		// creating empty HashMap object of type <String, String>
		HashMap<String, String> hashMap = new HashMap<String, String>();

		// checking empty even before adding any Key-Value pairs
		boolean isEmpty1 = hashMap.isEmpty();

		System.out.println("1. Checking Empty"
				+ " before adding any entries : " + isEmpty1);

		// adding key-value pairs to HashMap object
		hashMap.put("Google", "Sundar Pichai");
		hashMap.put("Facebook", "Mark Zuckerberg");
		hashMap.put("LinkedIn", "Reid Hoffman");
		hashMap.put("Apple", "Steve Jobs");
		hashMap.put("Microsoft", "Bill Gates");

		// checking empty adding few entries
		boolean isEmpty2 = hashMap.isEmpty();

		System.out.println("\n2. Checking Empty"
				+ " before adding any entries : " + isEmpty2);
	}
}

Output:

1. Checking Empty before adding any entries : true

2. Checking Empty before adding any entries : false

 

References:

 

Happy Coding !!
Happy Learning !!