What is the HashMap clear() method in Java?
The clear function in Java for HashMaps clears and removes all of the keys and values, or mappings, from the specified HashMap. This function is accessed as java.util.HashMap.clear().
Syntax
Hash_Map.clear()
Parameters and return value
Parameters: This method does not take any parameters.
Return value: Calling this method clears the HashMap.
Code
Let’s have a look at a coding example of how to use this method to clear a hash mapping.
// import the util lib from Javaimport java.util.*;class HelloWorld {public static void main( String args[] ) {{// Creating an empty HashMap based on our dataHashMap<Integer, String> hash_map = new HashMap<Integer, String>();// Introduce some data in the hashmaphash_map.put(10, "Apple");hash_map.put(20, "Banana");hash_map.put(30, "Orange");// Lets have a look at the HashMapSystem.out.println("Hashmap: "+ hash_map);// apply the clear method to the hashmaphash_map.clear();// Lets have a look a look at the hashmapSystem.out.println("After applying clear method: " + hash_map);}}}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved