Java TreeSet pollFirst() Method

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

Definition

In Java, pollFirst() removes the smallest (first) element from a TreeSet and returns it. If the set has no elements left, it returns null instead of throwing an exception.

Because TreeSet keeps elements sorted at all times, pollFirst() always hands out the lowest remaining value in O(log n) time, making it convenient for processing unique items in ascending priority.

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

Store the returned value in a wrapper variable so you can check for null safely.

Java
NavigableSet<Integer> jobs = new TreeSet<>(Arrays.asList(104, 101, 109));
Integer nextJob = jobs.pollFirst();   // 101, jobs = [104, 109]
Integer empty = new TreeSet<Integer>().pollFirst();   // null
CallWhat it does
set.pollFirst()Removes and returns the smallest element, or null.
set.first()Reads the smallest element without removing it; throws if empty.
set.pollLast()Removes and returns the largest element instead.
while ((x = set.pollFirst()) != null)Processes every element from low to high.

In a natural-order TreeSet, null can never be an element, so a null result unambiguously means the set is empty.

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

// Declared in NavigableSet<E>

Parameters

ParameterDescription
NonepollFirst() takes no parameters.

Return Value

Return ValueDescription
EThe lowest element, which has now been removed from the set.
nullIf the set was empty (or if a null-tolerant comparator stored null first).

Compare with Similar Methods

Reading or popping the ends of a TreeSet:

MethodHow it differs
first()Reads the lowest element without removing it; throws on empty.
pollLast()Removes and returns the highest element instead.
last()Reads the highest element without removing it.
ArrayDeque.pollFirst()Pops the front of insertion order rather than sorted order.

Java Examples

Example 1 — Dispatch the Lowest Print Job ID First

Pick the lowest pending job ID from a sorted queue and leave the remaining jobs waiting.

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

public class TreeSetPollFirstJobs {
    public static void main(String[] args) {
        NavigableSet<Integer> printQueue = new TreeSet<>(Arrays.asList(308, 102, 215, 150));
        System.out.println("waiting jobs: " + printQueue);

        Integer dispatched = printQueue.pollFirst();
        System.out.println("printing job: " + dispatched);
        System.out.println("still waiting: " + printQueue);
    }
}

How It Works

  1. Sorted queue ready. Even though 308 arrived first, the TreeSet orders job IDs from lowest to highest: 102, 150, 215, 308.
  2. Pop the smallest ID. pollFirst() removes 102 from the tree and returns it in dispatched.
  3. Remaining queue intact. Only 150, 215, and 308 stay in printQueue.

Example 2 — Drain All Scheduled Slots in Chronological Order

Use a while loop with pollFirst() to process sorted 24-hour times until empty.

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

public class TreeSetPollFirstDrain {
    public static void main(String[] args) {
        NavigableSet<String> slots = new TreeSet<>(Arrays.asList("14:30", "09:00", "11:15", "09:00"));

        String slot;
        while ((slot = slots.pollFirst()) != null) {
            System.out.println("running slot " + slot + " (remaining: " + slots.size() + ")");
        }
        System.out.println("queue empty? " + slots.isEmpty());
    }
}

How It Works

  1. Unique sorted times. Zero-padded strings sort chronologically, and the duplicate "09:00" was already collapsed.
  2. Single-call drain loop. Assigning slots.pollFirst() inside the loop condition fetches the next time and stops cleanly at null.
  3. Shrinking in place. Each step cuts slots.size() by one until slots.isEmpty() becomes true.

Example 3 — Empty Set Safety: pollFirst() vs first()

Compare pollFirst() returning null on an empty set against first() throwing NoSuchElementException.

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

public class TreeSetPollFirstEmpty {
    public static void main(String[] args) {
        NavigableSet<Integer> empty = new TreeSet<>();

        Integer safe = empty.pollFirst();
        System.out.println("pollFirst on empty: " + safe);

        try {
            empty.first();
        } catch (NoSuchElementException e) {
            System.out.println("first() on empty: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Graceful empty handling. Storing the result in Integer catches null without any exception or crash.
  2. Throwing alternative. Calling first() on the same empty set immediately throws NoSuchElementException.
  3. Watch out for primitives. Writing int x = empty.pollFirst(); would compile and then crash with NullPointerException.

Frequently Asked Questions

It removes and returns the smallest (first) element in the TreeSet, or returns null if the set is empty.
first() only reads the smallest element and throws NoSuchElementException if empty. pollFirst() removes it and returns null when empty.
Yes. When the set is not empty, the smallest element is removed from the set.
If the set is empty, pollFirst() returns null, and Java fails when trying to unbox null into a primitive int. Use Integer and check for null.
Java 6 (JDK 1.6), as part of the NavigableSet interface.

Next: pollLast()

Remove and return the largest element, or null if the set is empty.

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

14 people found this page helpful