Last Updated : 06 Aug, 2025
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.
Java
// 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);
}
}
Initial HashMap: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=for} After clear(): {}Syntax of HashMap clear() Method
public void clear()
Example 2: Here, we will use the clear() method to clear a HashMap of String keys and Integer values.
Java
// 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);
}
}
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4