What is the SortedSet.first() function in Java?
The SortedSet.first() method is used to obtain the current lowest or first element in the SortedSet.
The
SortedSet.first()method is present in theSortedSetinterface inside thejava.utilpackage.
Let’s understand with the help of an example. Suppose that the SortedSet contains . The first or lowest element in the SortedSet is . Hence, the result of the SortedSet.first() method is .
When we add the elements in the
SortedSet, they get stored in the sorted form. If theSortedSetis ofStringtype, the elements get stored in alphabetical order, irrespective of string length.
Parameters
The SortedSet.first() method does not accept any parameters.
Return value
The SortedSet.first() method
returns the lowest member of the SortedSet.
Code
Let’s have a look at the code.
import java.io.*;import java.util.TreeSet;import java.util.SortedSet;class Main{public static void main(String args[]){SortedSet<Integer> s = new TreeSet<Integer>();s.add(6);s.add(8);s.add(5);s.add(3);s.add(9);System.out.println("First or lowest element of SortedSet is " + s.first());}}
Explanation
-
From lines 1 to 3, we import the required packages and classes.
-
In line 5, we make a
Mainclass. -
In line 7, we make a
main()function. -
In line 9, we create a
TreeSetofIntegertype. TheSortedSetis actually only inherited fromTreeSet, soSortedSetis an interface we cannot instantiate an object of. -
From lines 10 to 14, we use the
SortedSet.add()method to add the elements into theSortedSet. -
In line 16, we use the
SortedSet.first()method to get the lowest member or first element of theSortedSetand display the result with a message.
In this way, we can use the SortedSet.first() function in Java.