In Java, TreeSet.remove()
is used to remove a particular element from the TreeSet
.
The
TreeSet.remove()
method is present in theTreeSet
class inside thejava.util
package.
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
.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.Let’s understand with the help of an example.
We have TreeSet = [1,8,5,3,9]
:
The result of the TreeSet.remove()
method is [3,8].
In the example above:
TreeSet
.TreeSet
.TreeSet
, so nothing gets removed from TreeSet
.TreeSet
.Thus, the TreeSet
stores [3,8] in a sorted manner.
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);}}
Main
class.main
function.TreeSet
of Integer
type.TreeSet.add()
method to add the elements into the TreeSet
.TreeSet
.