In this shot, we will learn how to use the TreeMap.clear()
method in Java.
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:
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 [ ]
.
The TreeMap.clear()
method doesn’t accept any parameters.
The TreeMap.clear()
method doesn’t return anything.
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);}}
Main
class.main()
function.TreeMap
consisting of keys of type Integer
and values of type String
.TreeMap
using the TreeMap.put()
method.
In line 14, we displayed the original TreeMap
.TreeMap
using the TreeMap.clear()
method.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
.