What is the TreeMap.clear() method in Java?

In this shot, we will learn how to use the TreeMap.clear() method in Java.

Introduction

The TreeMap.clear() method is present in the TreeMap class inside the java.util package.

It is used to remove all the keys from the specified TreeMap.

Let’s understand with the help of an example. Suppose a TreeMap contains following key-value pairs:

  • Key: 1, Value: Educative
  • Key: 5, Value: Learn Coding
  • Key: 2, Value: Python
  • Key: 27, Value: C++

When we use TreeMap.clear() method on this TreeMap, it removes all keys from the TreeMap, making the TreeMap blank.

So, the result of the TreeMap.clear() method is [ ].

Parameter

The TreeMap.clear() method doesn’t accept any parameters.

Return

The TreeMap.clear() method doesn’t return anything.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
TreeMap<Integer, String> h1 = new TreeMap<Integer, String>();
h1.put(1, "Educative");
h1.put(5, "Python");
h1.put(2, "Java");
h1.put(27, "Learn Coding");
h1.put(9, "C++");
System.out.println("The TreeMap is: " + h1);
h1.clear();
System.out.println("The TreeMap after using TreeMap.clear() method is: " + h1);
}
}

Explanation:

  • In line 1, we imported the required package.
  • In line 2, we made a Main class.
  • In line 4, we made a main() function.
  • In line 6, we declared a TreeMap consisting of keys of type Integer and values of type String.
  • From lines 8 to 12, we inserted values in the TreeMap using the TreeMap.put() method. In line 14, we displayed the original TreeMap.
  • In line 16, we removed all the keys from the TreeMap using the TreeMap.clear() method.
  • In line 17, we displayed the current TreeMap (after removing all the keys) with a message.

So, this is how to use the TreeMap.clear() function to remove all the keys from the TreeMap.

Free Resources