Java TreeMap clear() Example

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

Signature

public void clear()

This method removes all of the mappings from this map. The map will be empty after this call returns.

Example

The following example shows the usage of java.util.TreeMap.clear() method.

import java.util.Map;
import java.util.TreeMap;

public class ClearMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String> treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Printing the elements of the TreeMap
        System.out.println("**Elements of \"treeMap1\" before clear()**");
        System.out.println("Size of treeMap1 is : "+treeMap1.size());
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
        //Lets clear the elements of the treeMap1
        treeMap1.clear();
        
        //Printing the elements of the TreeMap
        System.out.println("**Elements of \"treeMap1\" before clear()**");
        System.out.println("Size of treeMap1 is : "+treeMap1.size());
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
    }
}

Output

**Elements of "treeMap1" before clear()**
Size of treeMap1 is : 4
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 4 Value : Element4
Key : 5 Value : Element5
**Elements of "treeMap1" before clear()**
Size of treeMap1 is : 0

Leave a Reply

Your email address will not be published. Required fields are marked *