![]() |
VOOZH | about |
The clear() method is a built-in method of the TreeMap class in Java of the java.util package. This method is used to remove all key-value mappings from the TreeMap. And after invoking this method, the map becomes completely empty.
This method is very useful when we want to reset the map or discard all the existing entries without creating a new instance.
treeMap.clear();
Example 1: In this example, we are going to create a TreeMap with Integer keys and String values and then clear it using the clear() method.
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
TreeMap after clear(): {}
Explanation: Here, we have added entries to the map then we use the clear() method to remove all mappings. Then the TreeMap becomes empty.
Example 2: In this example, we are using a TreeMap where keys are of type String and values are of type Integer.
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
TreeMap after clear(): {}
Explanation: Here also the clear() method deletes all mappings from the map.
Important Points: