What is the TreeSet.remove() function in Java?

In Java, TreeSet.remove() is used to remove a particular element from the TreeSet.

The TreeSet.remove() method is present in the TreeSet class inside the java.util package.

Parameters

The TreeSet.remove() method takes the following parameter.

  • Element: The element to be removed from the TreeSet. element is of the same data type as TreeSet.

Return value

TreeSet.remove() returns a Boolean value and performs an operation accordingly.

  • True: When the element is present in the TreeSet and the method removes that element from the TreeSet.
  • False: When the element is not present in the TreeSet and the method doesn’t remove anything.

Example

Let’s understand with the help of an example.

We have TreeSet = [1,8,5,3,9]:

  • The first element to remove is 1.
  • The second element to remove is 5.
  • The third element to remove is 10.
  • The fourth element to remove is 9.

The result of the TreeSet.remove() method is [3,8].

In the example above:

  • Element 1 = 1, which is present in and gets removed from the TreeSet.
  • Element 2 = 5, which is present in and gets removed from the TreeSet.
  • Element 3 = 10, which is not present in the TreeSet, so nothing gets removed from TreeSet.
  • Element 4 = 9, which is present in and gets removed from the TreeSet.

Thus, the TreeSet stores [3,8] in a sorted manner.

Code

Let’s look at the code below.

import java.io.*;
import java.util.TreeSet;
class Main
{
public static void main(String args[])
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add(1);
tree_set.add(8);
tree_set.add(5);
tree_set.add(3);
tree_set.add(9);
tree_set.remove(1);
tree_set.remove(5);
tree_set.remove(10);
tree_set.remove(9);
System.out.println("TreeSet: " + tree_set);
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.
  • In line 4, we make a Main class.
  • In line 6, we make a main function.
  • In line 8, we declare a TreeSet of Integer type.
  • In lines 9 to 13, we use the TreeSet.add() method to add the elements into the TreeSet.
  • In lines 15 to 18, we remove the elements from the TreeSet.
  • In line 20, we display the result with a message.

Free Resources