1. Introduction
A HashMap in Java is used to store key-value pairs. It is part of the java.util package. There could be scenarios where you need to remove all the mappings from a HashMap and clear it. The HashMap class provides a method called clear() which is used for this purpose. In this blog post, we will illustrate how to clear a HashMap using the clear() method.
2. Program Steps
1. Create a HashMap and add some key-value pairs to it.
2. Print the original HashMap.
3. Clear the HashMap using the clear() method.
4. Print the HashMap again to show that it is empty.
3. Code Program
import java.util.HashMap;
import java.util.Map;
public class HashMapClear {
public static void main(String[] args) {
// Step 1: Create a HashMap and add some key-value pairs to it
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Cherry", 30);
// Step 2: Print the original HashMap
System.out.println("Original HashMap: " + map);
// Step 3: Clear the HashMap using the clear() method
map.clear();
// Step 4: Print the HashMap again to show that it is empty
System.out.println("HashMap after clear: " + map);
}
}
Output:
Original HashMap: {Apple=10, Banana=20, Cherry=30} HashMap after clear: {}
4. Step By Step Explanation
Step 1: A HashMap named map is created and initialized with three key-value pairs.
Step 2: The original HashMap is printed to the console, showing the three key-value pairs.
Step 3: The clear() method is called on the map object. This method removes all the mappings from the HashMap, leaving it empty.
Step 4: The HashMap is printed again to the console, showing that it is now empty as all the mappings have been cleared.