Thursday, October 23, 2025
HomeLanguagesJavaHow to Check the LinkedHashMap Size in Java?

How to Check the LinkedHashMap Size in Java?

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

  1. Create a size variable of integer data type and initialize it with 0.
  2. Start iterating through the LinkedHashMap and increment the size variable at each iteration.
  3. After completion of the iteration, print size variable.

Below is the implementation of the above approach:

Java




// Java Program to find the size of LinkedHashMap
import java.util.*;
public class LinkedHashMapSizeExample {
  
    public static void main(String[] args)
    {
  
        // LinkedHashMap Initialization
        LinkedHashMap<Integer, String> lhMapColors
            = new LinkedHashMap<Integer, String>();
  
        lhMapColors.put(1, "red");
        lhMapColors.put(2, "white");
        lhMapColors.put(3, "blue");
  
        // Create of size variable and initialize with 0
        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
  1. Create a size variable of integer data type and initialize it with the size() method.
  2. Print size variable.

Below is the implementation of the above approach:

Java




// Java Program to find the size of LinkedHashMap
import java.util.LinkedHashMap;
public class LinkedHashMapSizeExample {
  
    public static void main(String[] args)
    {
        // Initialize LinkedHashMap
        LinkedHashMap<Integer, String> lhMapColors
            = new LinkedHashMap<Integer, String>();
  
        // Add elements
        lhMapColors.put(1, "red");
        lhMapColors.put(2, "white");
        lhMapColors.put(3, "blue");
  
        // Create size variable and initialize
        // it with size() method
        int size = lhMapColors.size();
        System.out.println("Size of LinkedHashMap is "
                           + size);
    }
}


Output

Size of LinkedHashMap is 3
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS