This example shows how to check if the LinkedHashMap is empty in Java. This example also shows how to use the isEmpty method and size method to check if the LinkedHashMap is empty or not.
How to check if LinkedHashMap is empty in Java?
There are a couple of ways we can check if the LinkedHashMap is empty or not.
1. Using the isEmpty method
The isEmpty
method of the LinkedHashMap class returns true if the map object is empty.
1 |
public boolean isEmpty() |
The isEmpty
method returns false if is at least one key-value mapping in the LinkedHashMap object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.LinkedHashMap; public class LinkedHashMapCheckIfEmptyExample { public static void main(String[] args) { LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); //will print true, as there are no mappings System.out.println("LinkedHashMap empty? " + lhmap.isEmpty()); lhmap.put(1, "One"); lhmap.put(2, "Two"); //will print false, as there are 2 mappings in the LinkedHashMap System.out.println("LinkedHashMap empty? " + lhmap.isEmpty()); } } |
Output
1 2 |
LinkedHashMap empty? true LinkedHashMap empty? false |
2. Using the size method
You can also use the size
method of the LinkedHashMap class to check if the map is empty or not.
1 |
public int size() |
If the LinkedHashMap size is 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>(); //will print true, as there are no mappings System.out.println("LinkedHashMap empty? " + (lhmap.size() == 0)); lhmap.put(1, "One"); lhmap.put(2, "Two"); //will print false, as there are 2 mappings in the LinkedHashMap System.out.println("LinkedHashMap empty? " + (lhmap.size() == 0)); |
Output
1 2 |
LinkedHashMap empty? true LinkedHashMap empty? false |
What is the preferred way to check?
There is no significant difference between these two methods as far as performance is concerned. The isEmpty
method internally uses the size to determine if the map is empty.
Using the isEmpty
method is the preferred way to check as it makes code look cleaner and makes the purpose of the code clear as compared to the size
method approach.
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