The clear() method of the HashMap class in Java is used to remove all of the elements or mappings (key-value pairs) from a specified HashMap.
Example 2: Here, we will use the clear() method to clear a HashMap of Integer keys and String values.
// Clearing HashMap of Integer keys
// and String values
import java.util.HashMap;
public class GFG {
public static void main(String[] args) {
// Create a HashMap and add
// key-value pairs
HashMap<Integer, String> hm = new HashMap<>();
hm.put(10, "Geeks");
hm.put(15, "for");
hm.put(20, "Geeks");
hm.put(25, "Welcomes");
hm.put(30, "You");
// Print the initial HashMap
System.out.println("Initial HashMap: " + hm);
// Clear the HashMap
hm.clear();
// Print the HashMap after clearing
System.out.println("After clear(): " + hm);
}
}
Output
Initial HashMap: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=for}
After clear(): {}
Syntax of HashMap clear() Method
public void clear()
- Parameters: This method does not accept any parameters.
- Return Value: This method does not return any value.
Example 2: Here, we will use the clear() method to clear a HashMap of String keys and Integer values.
// Clearing HashMap of String keys
// and Integer values
import java.util.HashMap;
public class GFG {
public static void main(String[] args) {
// Create a HashMap and add key-value pairs
HashMap<String, Integer> hm = new HashMap<>();
hm.put("Geeks", 10);
hm.put("for", 15);
hm.put("Geeks", 20); // Overwrites the previous value for "Geeks"
hm.put("Welcomes", 25);
hm.put("You", 30);
// Print the initial HashMap
System.out.println("Initial HashMap: " + hm);
// Clear the HashMap
hm.clear();
// Print the HashMap after clearing
System.out.println("After clear(): " + hm);
}
}
Output
Initial HashMap: {Geeks=20, for=15, You=30, Welcomes=25}
After clear(): {}
Note: The HashMap will remain empty after invoking the clear() method, but the HashMap object still exists and can be reused.