Java HashMap.size()
In this tutorial, we will learn about the Java HashMap.size() function, and learn how to use this function to get the number of items in this HashMap, with the help of examples.
size()
HashMap.size() returns the number of key-value mappings in this HashMap.
The syntax of size() function is
size()
Returns
The function returns integer.
Examples
1. size() basic example
In this example, we will initialize a HashMap hashMap
with four mappings in it. To get the size of items in this HashMap, call size() method on this HashMap. Since there are four items in hashMap
, size() should return 4
.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "A");
hashMap.put(2, "B");
hashMap.put(3, "C");
hashMap.put(4, "D");
System.out.println("HashMap : " + hashMap);
int size = hashMap.size();
System.out.println("Size of this HashMap is : " + size);
}
}
Output
HashMap : {1=A, 2=B, 3=C, 4=D}
Size of this HashMap is : 4
2. size() – With empty HashMap
In this example, we will initialize an empty HashMap hashMap
. To get the size of items in this HashMap, call size() method on this HashMap. Since there no items in hashMap
, size() should return 0
.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
System.out.println("HashMap : " + hashMap);
int size = hashMap.size();
System.out.println("Size of this HashMap is : " + size);
}
}
Output
HashMap : {}
Size of this HashMap is : 0
3. size() – When HashMap is null
In this example, we will initialize a HashMap hashMap
with null. When we call size() method on this HashMap, it should throw java.lang.NullPointerException.
Java Program
import java.util.HashMap;
public class Example{
public static void main(String[] args) {
HashMap<Integer, String> hashMap = null;
System.out.println("HashMap : " + hashMap);
int size = hashMap.size();
System.out.println("Size of this HashMap is : " + size);
}
}
Output
HashMap : null
Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:8)
Conclusion
In this Java Tutorial, we have learnt the syntax of Java HashMap.size() function, and also learnt how to use this function with the help of examples.