Java HashMap size() - Get Map Size

Updated on November 11, 2024
size() header image

Introduction

The size() method in Java is a part of the HashMap class, which is crucial for managing collections of data where retrieval speed matters. The HashMap utilises a hash table to store key-value pairs, and knowing the number of these pairs (or size) is essential for various operations like resizing, iteration, and logic conditioning based on current collection size.

In this article, you will learn how to effectively use the size() method in different contexts with the HashMap class in Java. Explore the basic usage of getting the size of the map and see examples that integrate this function within larger code constructs.

Retrieving the Size of a HashMap

Basic Example of size()

  1. Initialize a HashMap and add some key-value pairs.

  2. Use the size() method to obtain the number of entries in the map.

    java
    import java.util.HashMap;
    
    public class Main {
        public static void main(String[] args) {
            HashMap<Integer, String> map = new HashMap<>();
            map.put(1, "Apple");
            map.put(2, "Banana");
            map.put(3, "Cherry");
    
            int size = map.size();
            System.out.println("The size of the map is: " + size);
        }
    }
    

    This code initializes a HashMap with three entries and uses the size() method to print the total number of pairs in the map, which will output "The size of the map is: 3."

Checking If the Map Is Empty

  1. Use the size() method to check if the map is empty before performing operations.

  2. Modify the map by clearing and checking the size again.

    java
    import java.util.HashMap;
    
    public class Main {
        public static void main(String[] args) {
            HashMap<Integer, String> map = new HashMap<>();
            map.put(1, "Apple");
    
            if(map.size() > 0) {
                System.out.println("Map is not empty");
            }
    
            map.clear(); // Clearing the map
    
            if(map.size() == 0) {
                System.out.println("Map is empty now");
            }
        }
    }
    

    The program first confirms that the map isn't empty by checking if the size is greater than zero. After clearing the map, it correctly identifies that the map is empty by showing that its size is zero.

Conclusion

The size() method in Java's HashMap class is simple yet fundamental to the efficient management of key-value pair collections. It returns the number of key-value mappings in the map and is indispensable when making decisions based on the current capacity of the map. With the demonstrated examples, integrate this method into Java applications to ensure more precise control over data manipulations and checks. This streamlined interaction with HashMap increases code robustness and reliability in Java programs.