SortedSet first() method in Java

The first() method of SortedSet interface in Java is used toReturns the first i.e., the lowest element currently in this set.

Syntax:

E first()

Where, E is the type of element maintained by this Set.

Parameters: This function does not accepts any parameter.

Return Value: It returns the first or the lowest element currently in the set.

Exceptions: It throws NoSuchElementException, if the set is empty.

Below programs illustrate the above method:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java program to demonstrate
// working of SortedSet
  
import java.util.SortedSet;
import java.util.TreeSet;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeSet and inserting elements
        SortedSet<Integer> s = new TreeSet<>();
  
        // Adding Element to SortedSet
        s.add(1);
        s.add(5);
        s.add(2);
        s.add(3);
        s.add(9);
  
        // Returning the lowest element from set
        System.out.print("Lowest element in set is : "
                         + s.first());
    }
}

chevron_right


Output:

Lowest element in set is : 1

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to illstrate the first()
// method of SortedSet interface
  
import java.util.SortedSet;
import java.util.TreeSet;
  
public class GFG {
    public static void main(String args[])
    {
        // Create an empty SortedSet
        SortedSet<Integer> s = new TreeSet<>();
  
        // Trying to access element from
        // empty set
        try {
            s.first();
        }
        catch (Exception e) {
            // throws NoSuchElementException
            System.out.println("Exception: " + e);
        }
    }
}

chevron_right


Output:

Exception: java.util.NoSuchElementException

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedSet.html#first()



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.