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
Call
What 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
Parameter
Description
None
pollFirst() takes no parameters.
Return Value
Return Value
Description
E
The lowest element, which has now been removed from the set.
null
If the set was empty (or if a null-tolerant comparator stored null first).