TreeMap clear() method in java

Let’s learn TreeMap clear() method in java.

TreeMap clear() method in java

clear() method of TreeMap class removes all of the mappings from this map. The map will be empty after this call returns.


public void clear()


clear() method do not accept any parameters.

Now let’s see example on TreeMap clear() method.

import java.util.TreeMap;
public class TreeMapClearMethodExample
   public static void main(String[] args)
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(8, "red");
      tm.put(12, "blue");
      tm.put(10, "yellow");
      tm.put(6, "green");
      tm.put(4, "violet");
      System.out.println("TreeMap before using clear() method: " + tm);
      // clearing TreeMap using clear() method
      System.out.println("TreeMap after using clear() method: " + tm);


TreeMap before using clear() method: {4=violet, 6=green, 8=red, 10=yellow, 12=blue}
TreeMap after using clear() method: {}

Also read – switch statement in java