English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java HashMap size() usage and example

Java HashMap Methods

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() parameter

size() method without any parameters.

size() return value

  • Returns the number of existing Key/Value Mapping number

Example: Java HashMap size()

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.

Java HashMap Methods