1. Introduction

In Java, a HashMap is a part of the java.util package and is used to store key-value pairs. It is essential to know how many key-value pairs (or entries) are in a HashMap, and for this, the size() method is used. This method returns the number of key-value mappings in the HashMap. In this blog post, we will explore how to use the size() method to get the size of a HashMap.

2. Program Steps

1. Create a HashMap and populate it with some key-value pairs.

2. Print the size of the original HashMap using the size() method.

3. Add some more elements to the HashMap.

4. Again, print the size of the updated HashMap using the size() method.

3. Code Program

import java.util.HashMap;
import java.util.Map;

public class HashMapSize {

    public static void main(String[] args) {

        // Step 1: Create a HashMap and populate it with some key-value pairs
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Banana", 20);
        map.put("Cherry", 30);

        // Step 2: Print the size of the original HashMap
        System.out.println("Size of the original HashMap: " + map.size());

        // Step 3: Add some more elements to the HashMap
        map.put("Date", 40);
        map.put("Elderberry", 50);

        // Step 4: Again, print the size of the updated HashMap
        System.out.println("Size of the updated HashMap: " + map.size());
    }
}

Output:

Size of the original HashMap: 3
Size of the updated HashMap: 5

4. Step By Step Explanation

Step 1: A HashMap named map is created and initialized with three key-value pairs.

Step 2: The size() method is called on the map object to get the number of key-value pairs in the HashMap, and the size is printed to the console, which is 3.

Step 3: Two more key-value pairs are added to the HashMap, increasing the size to 5.

Step 4: The size() method is again called on the updated map object, and the new size, 5, is printed to the console, reflecting the addition of two more elements.