Home Java TreeSet Methods first() Java TreeSet first() Method 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.
SortedSet<Double> lapTimes = new TreeSet<>(Arrays.asList(62.4, 58.9, 60.1));
double fastest = lapTimes.first(); // 58.9 (still in lapTimes) Call What 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.util.TreeSet<E>
public E first()
// Declared in SortedSet<E> Parameters Parameter Description None first() takes no parameters.
Return Value Return Value Description 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:
Method How 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 1. Fastest lap time 2. First contact and comparator 3. Empty set guard Example 1 — Read the Fastest Race Lap Without Modifying the Leaderboard Store lap times in seconds and read the winning fastest lap with first().
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());
}
} all laps: [59.2, 61.8, 63.5]
fastest lap: 59.2
size still: 3 How It Works Fastest sits on the left. Natural ascending order puts 59.2 at the beginning of the sorted lap times.Read-only peek. Calling first() returns 59.2 into fastest while keeping all three laps in the set.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().
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());
}
} first alphabetically: Eli
reverseOrder set: [Zara, Mina, Eli]
first in reverse: Zara How It Works Ascending string minimum. Under natural order, "Eli" precedes "Mina" and "Zara", so first() returns "Eli".Comparator redefines first. Copying into a reverseOrder() set puts "Zara" at the front of the tree.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.
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());
}
}
} safe check: none
empty first(): NoSuchElementException How It Works Check before reading. Testing queue.isEmpty() skips first() when no elements exist.Uncaught call throws. Calling first() directly on an empty tree immediately raises NoSuchElementException.Non-throwing option. Use pollFirst() instead if you want null and want to remove the item.Frequently Asked Questions What does TreeSet first() do? It returns the lowest (first) element in the TreeSet according to its ordering without removing it.
What happens when you call first() on an empty TreeSet? It throws NoSuchElementException. Check isEmpty() first or use pollFirst() if you prefer null.
Does first() remove the element? No. Use pollFirst() when you want to read and remove the lowest element at the same time.
Can first() return the largest number? Yes, if the TreeSet was created with Comparator.reverseOrder() or another descending comparator, because first() follows the set ordering.
How fast is first() on a TreeSet? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion