This example shows how to get LinkedHashMap size in Java (LinkedHashMap length). This example also shows how to get the number of mappings stored in the LinkedHashMap using the size method.
How to get LinkedHashMap size in Java?
The size
method of the LinkedHashMap class returns the number of mappings stored in the LinkedHashMap object.
1 |
public int size() |
The size
method returns an int value equal to the key-value mapping stored in the map object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.LinkedHashMap; public class LinkedHashMapSizeExample { public static void main(String[] args) { LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); /* * To get the size of the LinkedHashMap, use the * size method. */ //this will return 0 as there are no mappings in the LinkedHashMap int size = lhmap.size(); System.out.println( "LinkedHashMap size is " + size ); //add some mappings lhmap.put(1, "one"); lhmap.put(2, "two"); //this will return 2 as there are mappings in the LinkedHashMap size = lhmap.size(); System.out.println( "LinkedHashMap size is " + size ); } } |
Output
1 2 |
LinkedHashMap size is 0 LinkedHashMap size is 2 |
You can use the size
method of the LinkedHashMap class to check if the LinkedHashMap is empty or not. To do that, you can get the size of the map object and then compare it with zero. If it is equal to zero, then the map is empty, otherwise not.
1 2 3 4 5 6 7 8 9 10 |
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); if( lhmap.size() == 0 ){ System.out.println("LinkedHashMap is empty"); }else{ System.out.println("LinkedHashMap is not empty"); } //or a short cut System.out.println("is empty: " + (lhmap.size() == 0)); |
Output
1 2 |
LinkedHashMap is empty is empty: true |
This example is a part of the Java LinkedHashMap tutorial with examples.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashMap