Java TreeMap - clear() Method
The java.util.TreeMap.clear() method is used to clear all key-value mappings from this map. This method makes the map empty with a size of zero.
Syntax
public void clear()
Parameters
No parameter is required.
Return Value
void type.
Exception
NA
Example:
In the example below, the java.util.TreeMap.clear() method is used to clear all key-value mappings from the given map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treemap TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>(); //populating the map MyMap.put(102, "John"); MyMap.put(103, "Marry"); MyMap.put(101, "Kim"); MyMap.put(104, "Jo"); //printing the map System.out.println("Before applying clear() method."); System.out.println("MyMap contains: " + MyMap); MyMap.clear(); //printing the map System.out.println("\nAfter applying clear() method."); System.out.println("MyMap contains: " + MyMap); } }
The output of the above code will be:
Before applying clear() method. MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo} After applying clear() method. MyMap contains: {}
❮ Java.util - TreeMap