The TreeSet.first()
method obtains the first element in the TreeSet
.
This method is present in the
TreeSet
class inside thejava.util
package.
The TreeSet.first()
method does not take any parameters.
Element
: It returns the lowest member of the TreeSet
.Let’s understand with the help of an example.
We have a TreeSet
: [1,8,5,3,9]
The first element in the TreeSet
is 1.
The result of the TreeSet.first()
method is 1.
Note: When we add the elements in the
TreeSet
, they get stored in the sorted form. If theTreeSet
is ofString
type, the elements get stored in alphabetical order, irrespective of string length.
Let’s take a look at the code snippet 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(0);System.out.println("First element of TreeSet is " + tree_set.first());}}
In lines 1 and 2, we import the required packages and classes.
In line 4, we create a Main
class.
In line 6, we create a main
function.
In line 8, we declare a TreeSet
of Integer
type.
In lines 9 to 13, we add the elements into the TreeSet
by using the TreeSet.add()
method.
In line 14, we get the lowest member or the first element of the TreeSet
using TreeSet.first()
method and display the result with a message.
In this way, we can use the TreeSet.first()
method to get the first element of the TreeSet
.