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=Geeks, 2=For, 1=Geeks}
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
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args)
{
LinkedHashMap<Integer, String> hm1
= new LinkedHashMap<Integer, String>();
System.out.println(
"Given LinkedHashMap is "
+ (hm1.size() == 0 ? "empty" : "not empty" ));
hm1.put( 3 , "Geeks" );
hm1.put( 2 , "For" );
hm1.put( 1 , "Geeks" );
int lhmSize = hm1.size();
if (lhmSize == 0 )
System.out.println(
"Given LinkedHashMap is empty" );
else
System.out.println(
"Given LinkedHashMap is not empty" );
}
}
|
OutputGiven 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
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args)
{
LinkedHashMap<Integer, String> hm1
= new LinkedHashMap<Integer, String>();
System.out.println(
"Given LinkedHashMap is "
+ (hm1.isEmpty() ? "empty" : "not empty" ));
hm1.put( 3 , "Geeks" );
hm1.put( 2 , "For" );
hm1.put( 1 , "Geeks" );
boolean lhmSize = hm1.isEmpty();
if (lhmSize)
System.out.println(
"Given LinkedHashMap is empty" );
else
System.out.println(
"Given LinkedHashMap is not empty" );
}
}
|
OutputGiven LinkedHashMap is empty
Given LinkedHashMap is not empty
Time Complexity: O(1)