Course contentsShow
← Java
Lesson 1097 of 2,87025. Set ImplementationsFree lesson

PollFirst and PollLast: Retrieving and Removing Extreme Elements

Removing and returning the first (lowest) or last (highest) element from a NavigableSet.

PollFirst and PollLast: Retrieving and Removing Extreme Elements

What you'll learn: How to remove and return the smallest or largest element from a NavigableSet in a single operation.

The Core Concept

While you've seen how to find elements near the extremes using lower, floor, higher, and ceiling, sometimes you need to actually remove the smallest or largest element while retrieving it. NavigableSet provides pollFirst() and pollLast() for exactly this purpose.

Think of it like a jar of coins sorted by value. pollFirst() reaches in, grabs the smallest coin, hands it to you, and removes it from the jar—all in one action. pollLast() does the same with the largest coin.

The Methods

pollFirst() removes and returns the lowest element in the set. If the set is empty, it returns null.

pollLast() removes and returns the highest element in the set. If the set is empty, it returns null.

TreeSet<Integer> scores = new TreeSet<>();
scores.add(85);
scores.add(92);
scores.add(78);
scores.add(95);

Integer lowest = scores.pollFirst();  // Returns 78, removes it
Integer highest = scores.pollLast();  // Returns 95, removes it

// Now scores contains only {85, 92}

When to Use Poll Operations

These methods are perfect for priority queue-like behavior where you process items in order and remove them as you go. They're also null-safe: you can check the return value to see if the set had any elements.

Integer next = scores.pollFirst();
if (next != null) {
    // Process the element
}

Key Takeaway: pollFirst() and pollLast() atomically retrieve and remove the extreme elements from a NavigableSet, making them ideal for processing sorted data in order while consuming it.