Java TreeMap pollFirstEntry() Method

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

Definition

In Java, pollFirstEntry() removes the mapping with the lowest key from a TreeMap and returns it, or returns null if the map is empty. It combines firstEntry() and remove() in one O(log n) step.

The returned entry is a snapshot of the removed mapping, so it is still readable after the removal. Added in Java 6 with NavigableMap, it turns a TreeMap into a simple priority queue keyed by sort order.

An instance method of java.util.TreeMap, added in Java 6 (JDK 1.6) with the NavigableMap interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

Each call takes the current lowest mapping out of the map.

Java
TreeMap<Integer, String> tasks = new TreeMap<>();
tasks.put(2, "review PR");
tasks.put(1, "fix outage");
Map.Entry<Integer, String> e = tasks.pollFirstEntry();   // 1=fix outage
// tasks is now {2=review PR}
CallWhat it does
map.pollFirstEntry()Removes and returns the lowest entry, or null.
map.firstEntry()Same entry without removing it.
map.headMap(k).clear()Removes every key below k at once.

Unlike Queue.remove() or firstKey(), pollFirstEntry never throws on an empty map; the null result doubles as the loop-ending signal.

Library declarations
Java
// java.util.TreeMap<K, V>
public Map.Entry<K, V> pollFirstEntry()

// Declared in NavigableMap<K, V> (Java 6)

Parameters

ParameterDescription
(none)pollFirstEntry takes no parameters.

Return Value

Return ValueDescription
Map.Entry<K, V>Snapshot of the removed mapping with the lowest key.
nullThe map (or view) was empty; nothing was removed.

Compare with Similar Methods

Ways to take entries off the low end:

MethodHow it differs
pollLastEntry()Removes the highest entry instead.
firstEntry()Looks without removing.
remove(firstKey())Two steps, and firstKey() throws when empty.
headMap(k).clear()Bulk removal of a whole low range.

Java Examples

Example 1 — Process Tasks by Priority Number

Priority 1 is most urgent, so the lowest key is always the next task to do.

Java
import java.util.Map;
import java.util.TreeMap;

public class TreeMapPollFirstEntryPriority {
    public static void main(String[] args) {
        TreeMap<Integer, String> tasks = new TreeMap<>();
        tasks.put(3, "write tests");
        tasks.put(1, "fix outage");
        tasks.put(2, "review PR");

        while (!tasks.isEmpty()) {
            Map.Entry<Integer, String> next = tasks.pollFirstEntry();
            System.out.println("doing P" + next.getKey() + ": " + next.getValue());
        }
        System.out.println("left: " + tasks);
    }
}

How It Works

  1. Most urgent first. Although "write tests" was added first, key 1 is the smallest, so the outage is handled before anything else.
  2. Each poll shrinks the map. Every call removes the entry it returns, and the next call sees the remaining lowest key, giving P1, P2, P3.
  3. Drained completely. The loop stops once isEmpty() is true, and the map prints as {}.

Example 2 — Hand Out a Single Coupon

Polling twice shows the null result, and the polled entry rejects setValue.

Java
import java.util.Map;
import java.util.TreeMap;

public class TreeMapPollFirstEntryCoupon {
    public static void main(String[] args) {
        TreeMap<String, Integer> coupons = new TreeMap<>();
        coupons.put("SPRING10", 10);

        Map.Entry<String, Integer> taken = coupons.pollFirstEntry();
        System.out.println("taken: " + taken + ", left: " + coupons);
        System.out.println("poll again: " + coupons.pollFirstEntry());
        try {
            taken.setValue(15);
        } catch (UnsupportedOperationException e) {
            System.out.println("setValue on polled entry: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Taken out, still readable. The snapshot prints SPRING10=10 even though the map is already empty.
  2. No coupon, no exception. The second poll finds nothing and simply returns null.
  3. A removed mapping cannot be edited. setValue(15) throws, which is sensible: there is no longer any tree node to write the value into.

Example 3 — Expire Sessions Older Than a Cutoff

Polling a headMap view removes the oldest sessions from the real map and stops at the cutoff.

Java
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class TreeMapPollFirstEntryExpire {
    public static void main(String[] args) {
        TreeMap<Integer, String> sessions = new TreeMap<>();
        sessions.put(5, "ann");
        sessions.put(18, "raj");
        sessions.put(26, "lee");
        sessions.put(40, "mo");

        NavigableMap<Integer, String> stale = sessions.headMap(20, false);
        for (Map.Entry<Integer, String> e = stale.pollFirstEntry(); e != null; e = stale.pollFirstEntry()) {
            System.out.println("expired " + e.getValue() + " (login at " + e.getKey() + ")");
        }
        System.out.println("active: " + sessions);
    }
}

How It Works

  1. A window of old logins. headMap(20, false) covers minutes 5 and 18 only; 26 and 40 are outside the view.
  2. Polling the view edits the map. Each pollFirstEntry on stale deletes that session from sessions as well, because the view is live.
  3. The cutoff ends the loop. Once 5 and 18 are gone the view is empty, the poll returns null, and the newer sessions survive untouched.

Frequently Asked Questions

It removes the mapping with the lowest key and returns it as a snapshot entry, or returns null if the map is empty.
No. It returns null, which makes it convenient as a loop condition.
Both return the lowest entry; pollFirstEntry() also removes it from the map.
Yes, as long as priorities (keys) are unique: put tasks by priority and take them with pollFirstEntry(). For duplicate priorities, store a list per key or use PriorityQueue.
Yes. Views are live, so the polled mapping is removed from the backing TreeMap.

Next: pollLastEntry()

Remove and return the pair with the largest key.

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

11 people found this page helpful