What is the TreeSet.first() function in Java?
The TreeSet.first() method obtains the first element in the TreeSet.
This method is present in the
TreeSetclass inside thejava.utilpackage.
Parameters
The TreeSet.first() method does not take any parameters.
Return
Element: It returns the lowest member of theTreeSet.
Example
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 theTreeSetis ofStringtype, the elements get stored in alphabetical order, irrespective of string length.
Code
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());}}
Explanation
-
In lines 1 and 2, we import the required packages and classes.
-
In line 4, we create a
Mainclass. -
In line 6, we create a
mainfunction. -
In line 8, we declare a
TreeSetofIntegertype. -
In lines 9 to 13, we add the elements into the
TreeSetby using theTreeSet.add()method. -
In line 14, we get the lowest member or the first element of the
TreeSetusingTreeSet.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.