Remove all elements from a treeMap in java

We can use clear() method to remove all elements from a treemap in java.

clear(): Removes all key-value pairs from this map.

Syntax:

public void clear()

Example

package com.w3schools;
 
import java.util.TreeMap;
 
public class Test {
	public static void main(String args[]){
		//Create TreeMap object.
		TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
 
		//Add objects to the TreeMap.
		treeMap.put(4, "Roxy");
		treeMap.put(2, "Sunil");
		treeMap.put(5, "Sandy");
		treeMap.put(1, "Munish");
		treeMap.put(3, "Pardeep");
 
		//Print the TreeMap object.
		System.out.println("TreeMap elements:");
		System.out.println(treeMap);
		//Remove treemap elements
		treeMap.clear();
		//Print the TreeMap object.
		System.out.println("TreeMap elements after clear operation:");
		System.out.println(treeMap);
	}
}

Output

TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
TreeMap elements after clear operation:
{}