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
LinkedHashMaphere.
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
LinkedHashMapclass. -
In line 4, we created a
LinkedHashMapobject with the namemap. -
In line 5, we used the
isEmptymethod to check if themapis empty.trueis returned as a result because themapobject is empty. -
In lines 6 and 7, we used the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 9, we used the
isEmptymethod to check if themapis empty.falseis returned as a result because themapobject is not empty.