This example shows how to get the HashMap size using the size method of the HashMap class. It is sometimes also referred to as HashMap length or number of key-value mappings stored in the HashMap.
How to get the HashMap size in Java?
The size
method of the HashMap class returns the number of entries or key-value mappings stored in the HashMap.
1 |
public int size() |
This method returns the number of mappings stored in the map object. The return type of the size
method is an int type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.HashMap; public class HashMapSizeExample { public static void main(String[] args) { //create new HashMap HashMap<String, String> hMapColors = new HashMap<String, String>(); //get the size using the size method System.out.println("Size is: " + hMapColors.size()); //add some key-value mappings hMapColors.put("1", "Red"); hMapColors.put("2", "Green"); hMapColors.put("3", "Blue"); System.out.println("HashMap contains " + hMapColors.size() + " mappings"); } } |
Output
1 2 |
Size is: 0 HashMap contains 3 mappings |
How to check if HashMap is empty using the size method?
You can compare the return value of the size
method with 0 to check if the HashMap is empty as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.HashMap; public class HashMapSizeExample { public static void main(String[] args) { //create new HashMap HashMap<String, String> hMapColors = new HashMap<String, String>(); System.out.println("is empty? " + (hMapColors.size() == 0) ); //add some key-value mappings hMapColors.put("1", "Red"); hMapColors.put("2", "Green"); System.out.println("is empty? " + (hMapColors.size() == 0) ); } } |
Output
1 2 |
is empty? true is empty? false |
This example is a part of the Java HashMap tutorial.
Please let me know your views in the comments section below.