Skip to content

Java TreeMap Clear Remove All Mappings Example

This example shows how to clear the TreeMap in Java. The example also shows how to remove all mappings or entries from the TreeMap using the clear method.

How to clear or remove all entries from TreeMap in Java?

There are a couple of ways using which you can remove all entries or key-value mappings from the TreeMap.

1. Using the clear method

The clear method of the TreeMap class removes all mappings from the TreeMap object.

The TreeMap becomes empty after this method call.


Please visit how to check if TreeMap is empty example to know more.

2. By assigning a new object

Instead of removing all the mappings, you can assign a new and empty TreeMap object to the same reference as given below.


Which method should I use?

Before deciding on which method to use, we need to understand the pros and cons of each of the methods.

Let’s first see the source code of the TreeMap clear method.

The clear method makes the internal variable size as 0 and assigns a null value to the root element. If the key-value objects are not referenced from anywhere else, they will become eligible for the garbage collection.

When you assign a new object to the same reference, all the key-value objects, as well as the old TreeMap object, becomes eligible for the garbage collection. Plus, it needs to create a new TreeMap object which is a costly operation in terms of performance. In the case of the clear method, the same map object can be reused.

Hence, using the clear method is the suggested approach to delete all mappings from the TreeMap.

This example is a part of the Java TreeMap Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.