Home Java TreeMap Methods firstEntry() Java TreeMap firstEntry() Method 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.
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" Call What 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.util.TreeMap<K, V>
public Map.Entry<K, V> firstEntry()
// Declared in NavigableMap<K, V> (Java 6) Parameters Parameter Description (none) firstEntry takes no parameters.
Return Value Return Value Description 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:
Java Examples 1. Cheapest option 2. null when empty 3. Read-only snapshot Example 1 — Pick the Cheapest Flight Prices are the keys, so the first entry is the lowest fare together with its flight number.
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());
}
} cheapest: 89=LH 210
flight LH 210 costs 89
fares still listed: 3 How It Works 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.Entry printing format. Concatenating the entry produces 89=LH 210, the familiar key=value text.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.
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);
}
} waitlist is empty
position 2: Dara
position 4: Chen How It Works 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.Position decides, not arrival. Chen was added first, but Dara holds the smaller position number 2 and therefore heads the list.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.
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);
}
} setValue on firstEntry(): UnsupportedOperationException
after entrySet setValue: {apples=39, bananas=25} How It Works Snapshots refuse writes. The entry from firstEntry() is a detached copy, so setValue(39) throws UnsupportedOperationException and the map keeps 40.Iterator entries are the real nodes. The first element of entrySet() is the same lowest mapping, but its setValue writes straight into the tree.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 What does TreeMap firstEntry() return? A Map.Entry with the lowest key and its value, or null if the map is empty.
What is the difference between firstEntry() and firstKey()? firstEntry() returns key and value and gives null on an empty map; firstKey() returns only the key and throws NoSuchElementException on an empty map.
Why does setValue() on firstEntry() throw an exception? The entry is an immutable snapshot, so setValue throws UnsupportedOperationException. Use put(key, newValue) to change the map.
Does firstEntry() remove the entry? No. Use pollFirstEntry() to return and remove the lowest entry in one step.
Does the snapshot update if the map changes later? No. It keeps the key and value it had when firstEntry() was called; call the method again to see the current state.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion