Home Java TreeSet Methods last() Java TreeSet last() Method Definition In Java, last() returns the highest (last) element in the TreeSet without removing it from the tree.
It finds the rightmost node in O(log n) time. It works on whole sets and on range views like headSet(), making it ideal for grabbing a top score, latest ISO date, or highest matching item below a ceiling.
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 last() on a non-empty sorted set to read its greatest element.
SortedSet<Integer> scores = new TreeSet<>(Arrays.asList(72, 95, 88));
int best = scores.last(); // 95 (scores stays [72, 88, 95]) Call What it does set.last()Reads the highest element without modifying the set. set.first()Reads the lowest element without modifying the set. set.pollLast()Removes and returns the highest element (null if empty). set.headSet(100).last()Highest element strictly below 100.
Java 21 adds getLast() via SequencedSet as a synonym for last(); this guide keeps examples Java 8+ compatible.
Library declarations // java.util.TreeSet<E>
public E last()
// Declared in SortedSet<E> Parameters Parameter Description None last() takes no parameters.
Return Value Return Value Description EThe greatest element according to the set's ordering; the set stays unchanged.
Compare with Similar Methods Reading or finding elements near the top end:
Method How it differs first()Reads the lowest element at the opposite end. pollLast()Removes the highest element and returns null when empty. floor(e)Finds the greatest element at or below e without throwing on empty. Collections.max(c)Scans any collection in O(n) time instead of O(log n).
Java Examples 1. Top leaderboard score 2. Latest ISO date 3. Empty set exception Example 1 — Peek at the Top Score and Runner-Up Cap Find the highest player score with last(), and combine with headSet() to inspect the second-best score.
import java.util.Arrays;
import java.util.TreeSet;
public class TreeSetLastScore {
public static void main(String[] args) {
TreeSet<Integer> scores = new TreeSet<>(Arrays.asList(410, 890, 620, 745));
int highest = scores.last();
int runnerUp = scores.headSet(highest).last();
System.out.println("scores: " + scores);
System.out.println("highest: " + highest);
System.out.println("runner-up: " + runnerUp);
}
} scores: [410, 620, 745, 890]
highest: 890
runner-up: 745 How It Works Rightmost node holds maximum. In ascending order, scores.last() reads 890 without touching the tree.Compose with a slice. headSet(highest) exposes everything strictly below 890, whose own last() is 745.Original set preserved. All four scores stay in scores after both peeks.Example 2 — Find the Latest Event Date From Sorted Date Strings Store YYYY-MM-DD dates in a TreeSet and read the latest scheduled date with last().
import java.util.Arrays;
import java.util.TreeSet;
public class TreeSetLastDate {
public static void main(String[] args) {
TreeSet<String> releases = new TreeSet<>(Arrays.asList("2026-03-14", "2026-11-02", "2026-07-21"));
System.out.println("chronological: " + releases);
System.out.println("latest date: " + releases.last());
releases.add("2027-01-09");
System.out.println("updated last: " + releases.last());
}
} chronological: [2026-03-14, 2026-07-21, 2026-11-02]
latest date: 2026-11-02
updated last: 2027-01-09 How It Works ISO strings sort chronologically. Zero-padded year-month-day text sorts naturally in calendar order inside TreeSet.Latest date at the tail. releases.last() returns "2026-11-02" in O(log n) time.Updates recalculate automatically. Inserting "2027-01-09" places it at the far right, making it the new last().Example 3 — Handle NoSuchElementException on an Empty Set or Empty Range Calling last() on an empty range slice throws NoSuchElementException; compare with floor().
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.TreeSet;
public class TreeSetLastEmpty {
public static void main(String[] args) {
TreeSet<Integer> nums = new TreeSet<>(Arrays.asList(30, 40, 50));
try {
nums.headSet(20).last();
} catch (NoSuchElementException e) {
System.out.println("empty headSet last(): " + e.getClass().getSimpleName());
}
System.out.println("safe floor(20): " + nums.floor(20));
}
} empty headSet last(): NoSuchElementException
safe floor(20): null How It Works Empty range view throws too. No value in [30, 40, 50] is below 20, so headSet(20) is empty and last() throws NoSuchElementException.Null-returning neighbour. Asking nums.floor(20) for the greatest element <= 20 returns null safely without throwing.Pick the right tool. Use last() when elements are guaranteed and floor() or pollLast() when empty sets can happen.Frequently Asked Questions What does TreeSet last() return? The highest (last) element in the TreeSet according to its ordering, without removing it.
What happens if I call last() on an empty TreeSet? It throws NoSuchElementException. Check isEmpty() first or call pollLast() to get null instead.
How is last() different from pollLast()? last() leaves the element inside the set; pollLast() removes and returns it.
Does last() work on a subSet() or headSet()? Yes. SortedSet views implement last() and return the highest element inside that view, or throw NoSuchElementException if the view is empty.
How fast is TreeSet last()? O(log n), following right links to the rightmost node in the red-black tree.
Next: lower() Find the largest element strictly less than a target, or null.
lower() 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.
12 people found this page helpful
Helpful Share Copy link Suggestion