English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java HashMap size() method returns the number of existing keys in the hash map/number of value mappings.
The syntax of the size() method is:
hashmap.size()
size() method without any parameters.
Returns the number of existing Key/Value Mapping number
import java.util.HashMap; class Main { public static void main(String[] args) { // Create HashMap HashMap<String, String> countries = new HashMap<>(); //Map Key/Value Insertion into HashMap countries.put("USA", "Washington"); countries.put("UK", "London"); countries.put("Canada", "Ottawa"); System.out.println("HashMap: ", + countries); //Get Key from HashMap/Number of Values int size = countries.size(); System.out.println("HashMap Size: ", + size());
Output Result
HashMap: {Canada=Ottawa, USA=Washington, UK=London} HashMap Size: 3
In the above example, we created a hash map named countries. Here, we used the size() method to get the number of elements existing in the hash map.Key/Value Mappingin number.