How to Check if LinkedHashMap is Empty in Java?
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. Here, Let’s illustrate the different approaches for checking if the LinkedHashMap is empty or not.
Example:
Input : {3=Beginner, 2=For, 1=Beginner} Output: Given LinkedHashMap is not empty Input : {} Output: Given LinkedHashMap is empty
1. Using the size() method :
- Create variable lhmSize.
- Store the value of the size of LinkedHashMap in it.
- If the size of the given LinkedHashMap is 0 then it is empty.
- Else it is not empty.
Below is the implementation of the above approach:
Java
// Java Program check if LinkedHashMap is empty or not import java.util.LinkedHashMap; public class Main { public static void main(String[] args) { // create an instance of LinkedHashMap LinkedHashMap<Integer, String> hm1 = new LinkedHashMap<Integer, String>(); // Using size() method to make comparison System.out.println( "Given LinkedHashMap is " + (hm1.size() == 0 ? "empty" : "not empty" )); // Add mappings using put method hm1.put( 3 , "Beginner" ); hm1.put( 2 , "For" ); hm1.put( 1 , "Beginner" ); int lhmSize = hm1.size(); if (lhmSize == 0 ) System.out.println( "Given LinkedHashMap is empty" ); else System.out.println( "Given LinkedHashMap is not empty" ); } } |
Output
Given LinkedHashMap is empty Given LinkedHashMap is not empty
Time Complexity: O(1)
2. Using the isEmpty() method :
- Create boolean variable lhmSize.
- Store the return value of the isEmpty() method.
- If the size of the given LinkedHashMap is 0 then isEmpty() method will return true.
- Else method will return false.
Below is the implementation of the above approach:
Java
// Java Program check if LinkedHashMap is empty or not import java.util.LinkedHashMap; public class Main { public static void main(String[] args) { // create an instance of LinkedHashMap LinkedHashMap<Integer, String> hm1 = new LinkedHashMap<Integer, String>(); // Using isEmpty() method to make comparison System.out.println( "Given LinkedHashMap is " + (hm1.isEmpty() ? "empty" : "not empty" )); // Add mappings using put method hm1.put( 3 , "Beginner" ); hm1.put( 2 , "For" ); hm1.put( 1 , "Beginner" ); boolean lhmSize = hm1.isEmpty(); if (lhmSize) System.out.println( "Given LinkedHashMap is empty" ); else System.out.println( "Given LinkedHashMap is not empty" ); } } |
Output
Given LinkedHashMap is empty Given LinkedHashMap is not empty
Time Complexity: O(1)
Contact Us