A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/java-treemap-clear-method/ below:

Java TreeMap clear() Method - GeeksforGeeks

Java TreeMap clear() Method

Last Updated : 11 Jul, 2025

The clear() method is a built-in method of the TreeMap class in Java of the java.util package. This method is used to remove all key-value mappings from the TreeMap. And after invoking this method, the map becomes completely empty.

This method is very useful when we want to reset the map or discard all the existing entries without creating a new instance.

Syntax of TreeMap clear() Method

treeMap.clear();

Examples of TreeMap clear() Method

Example 1: In this example, we are going to create a TreeMap with Integer keys and String values and then clear it using the clear() method.

Java
// Java program to demonstrate TreeMap clear() method
import java.util.TreeMap;

public class Geeks {
    
    public static void main(String[] args) {
        
        // Create a TreeMap with Integer keys
        TreeMap<Integer, String> tm = new TreeMap<>();

        // Add key-value pairs
        tm.put(10, "Geeks");
        tm.put(15, "4");
        tm.put(20, "Geeks");
        tm.put(25, "Welcomes");
        tm.put(30, "You");

        System.out.println("Initial Mappings are: " + tm);

        // Clear the TreeMap
        tm.clear();

        System.out.println("TreeMap after clear(): " + tm);
    }
}

Output
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
TreeMap after clear(): {}

Explanation: Here, we have added entries to the map then we use the clear() method to remove all mappings. Then the TreeMap becomes empty.

Example 2: In this example, we are using a TreeMap where keys are of type String and values are of type Integer.

Java
// Java program to demonstrate TreeMap clear() method
import java.util.TreeMap;

public class Geeks {
    
    public static void main(String[] args) {
        
        // Create a TreeMap with String keys
        TreeMap<String, Integer> tm = new TreeMap<>();

        // Add key-value pairs
        tm.put("Geeks", 10);
        tm.put("4", 15);
        tm.put("Geeks", 20); 
        tm.put("Welcomes", 25);
        tm.put("You", 30);

        System.out.println("Initial Mappings are: " + tm);

        // Clear the TreeMap
        tm.clear();

        System.out.println("TreeMap after clear(): " + tm);
    }
}

Output
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
TreeMap after clear(): {}

Explanation: Here also the clear() method deletes all mappings from the map.

Important Points:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4