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 the SortedSet interface inside the java.util package.

Let’s understand with the help of an example. Suppose that the SortedSet contains [1,5,3,9][1, 5, 3, 9]. The first or lowest element in the SortedSet is 11. Hence, the result of the SortedSet.first() method is 11.

When we add the elements in the SortedSet, they get stored in the sorted form. If the SortedSet is of String type, 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 Main class.

  • In line 7, we make a main() function.

  • In line 9, we create a TreeSet of Integer type. The SortedSet is actually only inherited from TreeSet, so SortedSet is an interface we cannot instantiate an object of.

  • From lines 10 to 14, we use the SortedSet.add() method to add the elements into the SortedSet.

  • In line 16, we use the SortedSet.first() method to get the lowest member or first element of the SortedSet and display the result with a message.

In this way, we can use the SortedSet.first() function in Java.

Free Resources