The syntax of the size()
method is:
hashmap.size()
Here, hashmap is an object of the HashMap
class.
size() Parameters
The size()
method does not take any parameters.
size() Return Value
- returns the number of key/value mappings present in the hashmap
Example: Java HashMap size()
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<String, String> countries = new HashMap<>();
// insert keys/values to the HashMap
countries.put("USA", "Washington");
countries.put("UK", "London");
countries.put("Canada", "Ottawa");
System.out.println("HashMap: " + countries);
// get the number of keys/values from HashMap
int size = countries.size();
System.out.println("Size of HashMap: " + size);
}
}
Output
HashMap: {Canada=Ottawa, USA=Washington, UK=London} Size of HashMap: 3
In the above example, we have created a hashmap named countries. Here, we have used the size()
method to get the number of key/value mappings present in the hashmap.