Java TreeSet first() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, first() returns the lowest (first) element currently stored in the TreeSet without removing it.

Because the red-black tree keeps elements sorted, reading the leftmost node takes O(log n) time. Note that under a descending comparator, first() returns the value sorted to the front of that ordering.

An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.

Syntax

Call first() on a non-empty set to peek at its minimum element.

Java
SortedSet<Double> lapTimes = new TreeSet<>(Arrays.asList(62.4, 58.9, 60.1));
double fastest = lapTimes.first();   // 58.9 (still in lapTimes)
CallWhat it does
set.first()Reads the lowest element without modifying the set.
set.last()Reads the highest element without modifying the set.
set.pollFirst()Removes the lowest element (returns null when empty).
if (!set.isEmpty()) set.first()Safe guard before reading an empty set.

Java 21 adds getFirst() via SequencedSet, which behaves the same as first(); this tutorial uses Java 8+ methods.

Library declarations
Java
// java.util.TreeSet<E>
public E first()

// Declared in SortedSet<E>

Parameters

ParameterDescription
Nonefirst() takes no parameters.

Return Value

Return ValueDescription
EThe smallest element according to the set's ordering; the set stays unchanged.

Compare with Similar Methods

Reading or removing extreme values in a TreeSet:

MethodHow it differs
last()Reads the highest element instead of the lowest.
pollFirst()Removes the lowest element and returns null if empty.
ceiling(e)Finds the lowest element at or above a chosen bound.
ArrayDeque.getFirst()Reads insertion-order front rather than sorted minimum.

Java Examples

Example 1 — Read the Fastest Race Lap Without Modifying the Leaderboard

Store lap times in seconds and read the winning fastest lap with first().

Java
import java.util.Arrays;
import java.util.TreeSet;

public class TreeSetFirstLap {
    public static void main(String[] args) {
        TreeSet<Double> laps = new TreeSet<>(Arrays.asList(63.5, 59.2, 61.8, 59.2));
        System.out.println("all laps: " + laps);

        double fastest = laps.first();
        System.out.println("fastest lap: " + fastest);
        System.out.println("size still:  " + laps.size());
    }
}

How It Works

  1. Fastest sits on the left. Natural ascending order puts 59.2 at the beginning of the sorted lap times.
  2. Read-only peek. Calling first() returns 59.2 into fastest while keeping all three laps in the set.
  3. Size unchanged. laps.size() stays 3 because first() never removes elements.

Example 2 — Alphabetical Directory and Reverse-Order First Element

Read the earliest contact alphabetically, then see what first() returns with Comparator.reverseOrder().

Java
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetFirstOrder {
    public static void main(String[] args) {
        TreeSet<String> names = new TreeSet<>(Arrays.asList("Zara", "Eli", "Mina"));
        System.out.println("first alphabetically: " + names.first());

        TreeSet<String> reversed = new TreeSet<>(Comparator.reverseOrder());
        reversed.addAll(names);
        System.out.println("reverseOrder set:     " + reversed);
        System.out.println("first in reverse:     " + reversed.first());
    }
}

How It Works

  1. Ascending string minimum. Under natural order, "Eli" precedes "Mina" and "Zara", so first() returns "Eli".
  2. Comparator redefines first. Copying into a reverseOrder() set puts "Zara" at the front of the tree.
  3. Front of active order. reversed.first() returns "Zara" because first() always follows the set's comparator.

Example 3 — Guard Against NoSuchElementException on an Empty TreeSet

Handle an empty set cleanly with isEmpty() and catch the exception when calling first() anyway.

Java
import java.util.NoSuchElementException;
import java.util.TreeSet;

public class TreeSetFirstEmpty {
    public static void main(String[] args) {
        TreeSet<Integer> queue = new TreeSet<>();

        System.out.println("safe check: " + (queue.isEmpty() ? "none" : queue.first()));
        try {
            queue.first();
        } catch (NoSuchElementException e) {
            System.out.println("empty first(): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Check before reading. Testing queue.isEmpty() skips first() when no elements exist.
  2. Uncaught call throws. Calling first() directly on an empty tree immediately raises NoSuchElementException.
  3. Non-throwing option. Use pollFirst() instead if you want null and want to remove the item.

Frequently Asked Questions

It returns the lowest (first) element in the TreeSet according to its ordering without removing it.
It throws NoSuchElementException. Check isEmpty() first or use pollFirst() if you prefer null.
No. Use pollFirst() when you want to read and remove the lowest element at the same time.
Yes, if the TreeSet was created with Comparator.reverseOrder() or another descending comparator, because first() follows the set ordering.
O(log n), because it follows left child links down the balanced red-black tree to the leftmost node.

Next: floor()

Find the largest element less than or equal to a target, or null.

floor() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful