Java – 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 ?

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 whether HashMap"
				+ " is 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 whether HashMap"
				+ " is Empty AFTER adding few entries : " 
				+ isEmpty2);
	}
}

Output:

1. Checking whether HashMap is Empty BEFORE adding any entries : true

2. Checking whether HashMap is Empty AFTER adding few entries : false

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to sort HashSet ?
Java - Conversion of ArrayList to Arrays in 2 ways