What is the LinkedHashMap.isEmpty method in Java?

A LinkedHashMap is the same as HashMap, except the LinkedHashMap maintains the insertion order, whereas the HashMap doesn’t. Internally, the LinkedHashMap uses the doubly-linked list to maintain the insertion order.

Read more about LinkedHashMap here.

The isEmpty method of LinkedHashMap is used to check if the specified LinkedHashMap is empty.

Syntax

public boolean isEmpty()

This method doesn’t take any argument.

This method returns true if the map doesn’t have any mappings. Otherwise, false will be returned.

Code

The following example shows how to use the isEmpty method.

import java.util.LinkedHashMap;
class LinkedHashMapisEmptyExample {
public static void main( String args[] ) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
System.out.println("\nChecking if LinkedHashMap is empty : "+ map.isEmpty());
map.put(1, "one");
map.put(2, "two");
System.out.println("\nAfter Adding some mappings to the map");
System.out.println("\nChecking if LinkedHashMap is empty : "+ map.isEmpty());
}
}

Explanation

In the code above:

  • In line 1, we imported the LinkedHashMap class.

  • In line 4, we created a LinkedHashMap object with the name map.

  • In line 5, we used the isEmpty method to check if the map is empty. true is returned as a result because the map object is empty.

  • In lines 6 and 7, we used the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 9, we used the isEmpty method to check if the map is empty. false is returned as a result because the map object is not empty.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources