How to Check the LinkedHashMap Size in Java?
Last Updated :
07 Jan, 2021
Size of LinkedHashMap can be obtained in multiple ways like by using an inbuilt function and by iterating through the LinkedHashMap.
Example:
Input : List : [1 : "John", 2 : "Tom", 3 : "Tim"]
Output: 3
Input : List : [1 : "John", 2 : "Tom"]
Output: 2
Approach 1: using Iteration
- Create a size variable of integer data type and initialize it with 0.
- Start iterating through the LinkedHashMap and increment the size variable at each iteration.
- After completion of the iteration, print size variable.
Below is the implementation of the above approach:
Java
import java.util.*;
public class LinkedHashMapSizeExample {
public static void main(String[] args)
{
LinkedHashMap<Integer, String> lhMapColors
= new LinkedHashMap<Integer, String>();
lhMapColors.put( 1 , "red" );
lhMapColors.put( 2 , "white" );
lhMapColors.put( 3 , "blue" );
int size = 0 ;
for (Map.Entry mapElement :
lhMapColors.entrySet()) {
size++;
}
System.out.println( "Size of LinkedHashMap is "
+ size);
}
}
|
Output
Size of LinkedHashMap is 3
Approach 2: Using size() Method
Syntax:
List.size()
Return Type:
Integer
- Create a size variable of integer data type and initialize it with the size() method.
- Print size variable.
Below is the implementation of the above approach:
Java
import java.util.LinkedHashMap;
public class LinkedHashMapSizeExample {
public static void main(String[] args)
{
LinkedHashMap<Integer, String> lhMapColors
= new LinkedHashMap<Integer, String>();
lhMapColors.put( 1 , "red" );
lhMapColors.put( 2 , "white" );
lhMapColors.put( 3 , "blue" );
int size = lhMapColors.size();
System.out.println( "Size of LinkedHashMap is "
+ size);
}
}
|
Output
Size of LinkedHashMap is 3
Share your thoughts in the comments
Please Login to comment...