VOOZH about

URL: https://www.geeksforgeeks.org/java/treeset-first-method-in-java/

⇱ TreeSet first() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TreeSet first() Method in Java

Last Updated : 22 Oct, 2025

The first method in Java’s TreeSet returns the lowest element in the set based on its natural ordering or a custom comparator.

Syntax

TreeSet<E> treeSet;
E firstElement = treeSet.first();

  • Parameters: This method does not take any parameters.
  • Return Value: Returns the first (lowest) element (smallest value in case of integers and lexicographically smallest in case of strings)
  • Throws: If the set is empty, it throws a NoSuchElementException

Note: TreeSet automatically sorts elements in ascending order, so first() always returns the element at the beginning of this order.

Example 1: Using first() with Integers


Output
TreeSet: [3, 8, 10, 25]
First (Lowest) Element: 3

Example 2: Using first() with Strings


Output
TreeSet: [Alice, Bob, Diana, John]
First (Lowest) Element: Alice

Example 3: Using first() with a Custom Comparator


Output
TreeSet (Descending Order): [15, 10, 5]
First Element (in Descending Order): 15

Example 4: When TreeSet is Empty


Output
Exception: java.util.NoSuchElementException



Comment