Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

treemap
clear
java
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
Use TreeMap.clear() method in Java

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.

RELATED TAGS

treemap
clear
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring