Example
In the last tutorial we shared how to remove a specific mapping from HashMap based on key. In this example we are going to see how to remove all the mappings from HashMap. We will be using clear() method of HashMap class to do this:
public void clear()
: Removes all of the mappings from this map. The map will be empty after this call returns.
Complete Code:
import java.util.HashMap; public class RemoveAllExample { public static void main(String[] args) { // Creating a HashMap of int keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); // Adding Key and Value pairs to HashMap hashmap.put(11,"Value1"); hashmap.put(22,"Value2"); hashmap.put(33,"Value3"); hashmap.put(44,"Value4"); hashmap.put(55,"Value5"); // Displaying HashMap Elements System.out.println("HashMap Elements: " + hashmap); // Removing all Mapping hashmap.clear(); // Displaying HashMap Elements after remove System.out.println("After calling clear():"); System.out.println("---------------------"); System.out.println("HashMap Elements: " + hashmap); } }
Output:
HashMap Elements: {33=Value3, 55=Value5, 22=Value2, 11=Value1, 44=Value4} After calling clear(): --------------------- HashMap Elements: {}
As you can see all the mappings of HashMap have been removed after calling clear() method and HashMap became empty after that.
Leave a Reply