Java TreeMap firstEntry() Method

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

Definition

In Java, firstEntry() returns the key/value pair with the lowest key in a TreeMap, as a Map.Entry. On an empty map it returns null instead of throwing, which is the main difference from firstKey().

The returned entry is a snapshot: it records the key and value at the moment of the call and does not support setValue. The method arrived in Java 6 with NavigableMap and runs in O(log n) time.

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

One call gives you both halves of the lowest mapping.

Java
TreeMap<Integer, String> fares = new TreeMap<>();
fares.put(145, "BA 902");
fares.put(89, "LH 210");
Map.Entry<Integer, String> e = fares.firstEntry();   // 89=LH 210
int price = e.getKey();          // 89
String flight = e.getValue();    // "LH 210"
CallWhat it does
map.firstEntry()Lowest entry, or null when empty.
map.firstEntry().getKey()Same key as firstKey() (but NPE if empty).
map.pollFirstEntry()Lowest entry, removed from the map.

Printing a Map.Entry gives key=value, the same format used inside a printed map. Import java.util.Map to name the type Map.Entry<K, V>.

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

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

Parameters

ParameterDescription
(none)firstEntry takes no parameters.

Return Value

Return ValueDescription
Map.Entry<K, V>A read-only snapshot of the mapping with the lowest key.
nullThe map is empty.

Compare with Similar Methods

Low-end methods compared:

MethodHow it differs
firstKey()Key only; throws NoSuchElementException when empty.
lastEntry()The entry at the high end.
pollFirstEntry()Same entry, but removed.
ceilingEntry(k)Lowest entry with a key of at least k.

Java Examples

Example 1 — Pick the Cheapest Flight

Prices are the keys, so the first entry is the lowest fare together with its flight number.

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

public class TreeMapFirstEntryFlights {
    public static void main(String[] args) {
        TreeMap<Integer, String> fares = new TreeMap<>();
        fares.put(145, "BA 902");
        fares.put(89, "LH 210");
        fares.put(112, "KL 1004");

        Map.Entry<Integer, String> cheapest = fares.firstEntry();
        System.out.println("cheapest: " + cheapest);
        System.out.println("flight " + cheapest.getValue() + " costs " + cheapest.getKey());
        System.out.println("fares still listed: " + fares.size());
    }
}

How It Works

  1. Price and flight in one call. The entry holds key 89 and value "LH 210", so no second lookup is needed to name the flight.
  2. Entry printing format. Concatenating the entry produces 89=LH 210, the familiar key=value text.
  3. Reading is not taking. size() is still 3 afterwards; only the poll methods remove what they return.

Example 2 — Show the Head of a Waitlist, Even When It Is Empty

A helper method checks the snapshot for null before reading it.

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

public class TreeMapFirstEntryWaitlist {
    static void describe(TreeMap<Integer, String> waitlist) {
        Map.Entry<Integer, String> head = waitlist.firstEntry();
        if (head == null) {
            System.out.println("waitlist is empty");
        } else {
            System.out.println("position " + head.getKey() + ": " + head.getValue());
        }
    }

    public static void main(String[] args) {
        TreeMap<Integer, String> waitlist = new TreeMap<>();
        describe(waitlist);

        waitlist.put(4, "Chen");
        waitlist.put(2, "Dara");
        describe(waitlist);

        waitlist.remove(2);
        describe(waitlist);
    }
}

How It Works

  1. No exception for an empty list. The first call gets null back, so the helper prints the empty message instead of crashing like firstKey() would.
  2. Position decides, not arrival. Chen was added first, but Dara holds the smaller position number 2 and therefore heads the list.
  3. Next in line. After position 2 is removed, the same helper reports Chen at position 4 without any extra bookkeeping.

Example 3 — Why firstEntry().setValue() Fails

The snapshot rejects changes; an entry taken from entrySet() iteration is live and accepts them.

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

public class TreeMapFirstEntrySnapshot {
    public static void main(String[] args) {
        TreeMap<String, Integer> stock = new TreeMap<>();
        stock.put("apples", 40);
        stock.put("bananas", 25);

        try {
            stock.firstEntry().setValue(39);
        } catch (UnsupportedOperationException e) {
            System.out.println("setValue on firstEntry(): " + e.getClass().getSimpleName());
        }

        Map.Entry<String, Integer> live = stock.entrySet().iterator().next();
        live.setValue(39);
        System.out.println("after entrySet setValue: " + stock);
    }
}

How It Works

  1. Snapshots refuse writes. The entry from firstEntry() is a detached copy, so setValue(39) throws UnsupportedOperationException and the map keeps 40.
  2. Iterator entries are the real nodes. The first element of entrySet() is the same lowest mapping, but its setValue writes straight into the tree.
  3. The simplest fix. Outside a loop, stock.put("apples", 39) does the same job; the entry-set route matters mainly while iterating.

Frequently Asked Questions

A Map.Entry with the lowest key and its value, or null if the map is empty.
firstEntry() returns key and value and gives null on an empty map; firstKey() returns only the key and throws NoSuchElementException on an empty map.
The entry is an immutable snapshot, so setValue throws UnsupportedOperationException. Use put(key, newValue) to change the map.
No. Use pollFirstEntry() to return and remove the lowest entry in one step.
No. It keeps the key and value it had when firstEntry() was called; call the method again to see the current state.

Next: firstKey()

Read the smallest key (throws when the map is empty).

firstKey() 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