Java TreeSet pollLast() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 6+

Definition

In Java, pollLast() removes the largest (last) element in the TreeSet and returns it, or returns null if the set is empty.

Keep in mind that "last" always follows the set's active ordering: under natural order it pops the maximum element, while under a reversed comparator it pops the minimum natural value.

An instance method of java.util.TreeSet (Java 6+ (added via NavigableSet in JDK 1.6)): 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 pollLast() and assign to a nullable reference type before checking for null.

Java
NavigableSet<Integer> bids = new TreeSet<>(Arrays.asList(120, 350, 210));
Integer topBid = bids.pollLast();   // 350, bids = [120, 210]
Integer none = new TreeSet<Integer>().pollLast();   // null
CallWhat it does
set.pollLast()Removes and returns the highest element, or null.
set.last()Peeks at the highest element without removing it; throws if empty.
set.pollFirst()Removes and returns the lowest element instead.
while ((x = set.pollLast()) != null)Drains elements from highest to lowest.

When a TreeSet uses Comparator.reverseOrder(), elements sit from largest to smallest, so pollLast() removes the smallest natural value.

Library declarations
Java
// java.util.TreeSet<E>  (since Java 6)
public E pollLast()

// Declared in NavigableSet<E>

Parameters

ParameterDescription
NonepollLast() takes no parameters.

Return Value

Return ValueDescription
EThe highest element in the set's ordering, now removed.
nullIf the set is empty (or if a custom comparator placed null last).

Compare with Similar Methods

Methods for working at the upper end of a TreeSet:

MethodHow it differs
last()Reads the highest element without modifying the set; throws if empty.
pollFirst()Pops the lowest element from the opposite end.
lower(e)Finds the element just below a given value without removing it.
ArrayDeque.pollLast()Removes the tail of insertion order, not the sorted maximum.

Java Examples

Example 1 — Pop the Winning Auction Bid While Keeping Runner-Ups

Remove the highest unique bid from a sorted auction set and inspect the runner-up bids left behind.

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

public class TreeSetPollLastAuction {
    public static void main(String[] args) {
        NavigableSet<Integer> bids = new TreeSet<>(Arrays.asList(140, 290, 185, 290));
        System.out.println("unique bids: " + bids);

        Integer winner = bids.pollLast();
        System.out.println("winning bid popped: " + winner);
        System.out.println("remaining runner-up bids: " + bids);
    }
}

How It Works

  1. Deduplicated ascending bids. Two 290 bids collapse into one, leaving three unique amounts sorted up to 290.
  2. Pop the top bid. pollLast() returns 290 and takes it out of the tree in O(log n) time.
  3. Runner-ups stay ready. [140, 185] remain in bids so a second pollLast() would immediately fetch 185.

Example 2 — Hand Out Leaderboard Medals From Highest Score Down

Drain a score set from highest to lowest using pollLast() until none remain.

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

public class TreeSetPollLastMedals {
    public static void main(String[] args) {
        NavigableSet<Integer> leaderboard = new TreeSet<>(Arrays.asList(68, 95, 84));
        int rank = 1;

        Integer top;
        while ((top = leaderboard.pollLast()) != null) {
            System.out.println("rank #" + rank + ": " + top);
            rank++;
        }
        System.out.println("left in set: " + leaderboard);
    }
}

How It Works

  1. Descending consumption without reversing. Even though the tree stores elements low-to-high, pollLast() walks from 95 down to 68.
  2. Clean termination. Once 68 is popped, the fourth pollLast() returns null and exits the loop.
  3. Original set emptied. All three scores were consumed, leaving [] at the end.

Example 3 — How reverseOrder() Flips pollLast(), Plus Empty Sets

With Comparator.reverseOrder(), pollLast() pops the smallest number; an empty set returns null.

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

public class TreeSetPollLastReversed {
    public static void main(String[] args) {
        NavigableSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder());
        desc.addAll(Arrays.asList(10, 50, 30));
        System.out.println("set order: " + desc);
        System.out.println("pollLast pops: " + desc.pollLast());
        System.out.println("after pop: " + desc);

        desc.clear();
        System.out.println("pollLast on empty: " + desc.pollLast());
    }
}

How It Works

  1. Comparator defines last. Because desc orders numbers from 50 down to 10, the last element in tree order is 10.
  2. Minimum removed. pollLast() removes and returns 10, leaving [50, 30].
  3. Null after clear. Emptying the set causes the next pollLast() to return null without throwing.

Frequently Asked Questions

It removes and returns the highest (last) element according to the TreeSet ordering, or returns null if the set is empty.
last() leaves the element in the set and throws NoSuchElementException when empty. pollLast() removes the element and returns null when empty.
It removes and returns the last element in that reversed ordering, which is the smallest natural value in the set.
Yes. Finding and removing the rightmost node in a red-black tree takes O(log n) time.
Only if the TreeSet uses a null-friendly comparator that placed null at the end of the set; under natural order null cannot be stored at all.

Next: remove()

Delete a matching element in O(log n) time and report whether it existed.

remove() 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.

15 people found this page helpful