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.
Initialize a HashMap
and add some key-value pairs.
Use the size()
method to obtain the number of entries in the map.
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."
Use the size()
method to check if the map is empty before performing operations.
Modify the map by clearing and checking the size again.
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.
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.