Write a Java program to delete all elements from a given Tree Map


This Java program demonstrates how to remove all entries from a TreeMap using the clear() method. First, a TreeMap object s1 is created and initialized with five key-value pairs using the put() method. Then, the content of the s1 TreeMap is printed using the println() method.

The clear() method is invoked on the s1 TreeMap object, which removes all the entries from the TreeMap. Finally, the empty TreeMap is printed using the println() method.

Source Code

import java.util.*;
import java.util.Map.Entry;  
public class DeleteAll
{  
	public static void main(String args[])
	{  
		TreeMap<Integer,String> s1 = new TreeMap<Integer,String>();		
		s1.put(101, "John");
		s1.put(102, "Joes");
		s1.put(103, "Smith");
		s1.put(104, "Charles");
		s1.put(105, "George");
 
		System.out.println("Given TreeMap : "+s1);
		s1.clear();
		System.out.println("New TreeMap : "+s1);
	}
}

Output

Given TreeMap : {101=John, 102=Joes, 103=Smith, 104=Charles, 105=George}
New TreeMap : {}

Example Programs