Java TreeSet last() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

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.

Java
SortedSet<Integer> scores = new TreeSet<>(Arrays.asList(72, 95, 88));
int best = scores.last();   // 95 (scores stays [72, 88, 95])
CallWhat 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
// java.util.TreeSet<E>
public E last()

// Declared in SortedSet<E>

Parameters

ParameterDescription
Nonelast() takes no parameters.

Return Value

Return ValueDescription
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:

MethodHow 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

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.

Java
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);
    }
}

How It Works

  1. Rightmost node holds maximum. In ascending order, scores.last() reads 890 without touching the tree.
  2. Compose with a slice. headSet(highest) exposes everything strictly below 890, whose own last() is 745.
  3. 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().

Java
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());
    }
}

How It Works

  1. ISO strings sort chronologically. Zero-padded year-month-day text sorts naturally in calendar order inside TreeSet.
  2. Latest date at the tail. releases.last() returns "2026-11-02" in O(log n) time.
  3. 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().

Java
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));
    }
}

How It Works

  1. Empty range view throws too. No value in [30, 40, 50] is below 20, so headSet(20) is empty and last() throws NoSuchElementException.
  2. Null-returning neighbour. Asking nums.floor(20) for the greatest element <= 20 returns null safely without throwing.
  3. Pick the right tool. Use last() when elements are guaranteed and floor() or pollLast() when empty sets can happen.

Frequently Asked Questions

The highest (last) element in the TreeSet according to its ordering, without removing it.
It throws NoSuchElementException. Check isEmpty() first or call pollLast() to get null instead.
last() leaves the element inside the set; pollLast() removes and returns it.
Yes. SortedSet views implement last() and return the highest element inside that view, or throw NoSuchElementException if the view is empty.
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

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.

12 people found this page helpful