Java TreeMap firstKey() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, firstKey() returns the lowest key currently in a TreeMap: the key that comes first in the map's sort order. It only reads the map; nothing is removed.

"Lowest" is decided by the map's ordering. With natural ordering it is the smallest number or the alphabetically first string; with a reverse comparator it is the largest value. The method comes from SortedMap and runs in O(log n) time, following left children down from the root.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. 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

No arguments; you get the key itself, not the value.

Java
TreeMap<String, String> slots = new TreeMap<>();
slots.put("14:00", "Dentist");
slots.put("09:30", "Stand-up");
String first = slots.firstKey();   // "09:30"
CallWhat it does
map.firstKey()The lowest key; throws on an empty map.
map.firstEntry()Key and value together, or null when empty.
map.get(map.firstKey())The value that belongs to the lowest key.

The return type is K, so for a TreeMap<Integer, ...> you can write int low = map.firstKey();. That unboxing is safe here because firstKey never returns null for a natural-order map; it throws instead.

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

// Declared in SortedMap<K, V>

Parameters

ParameterDescription
(none)firstKey takes no parameters.

Return Value

Return ValueDescription
KThe first (lowest) key according to the map's ordering.

Compare with Similar Methods

Methods that look at the low end of a TreeMap:

MethodHow it differs
firstEntry()Returns a key/value snapshot, or null when empty.
lastKey()The opposite end: the highest key.
pollFirstEntry()Returns and removes the lowest entry.
ceilingKey(k)The lowest key that is at least k.

Java Examples

Example 1 — Find the Next Appointment of the Day

Times are zero-padded strings, so the alphabetically first key is also the earliest time.

Java
import java.util.TreeMap;

public class TreeMapFirstKeyAppointments {
    public static void main(String[] args) {
        TreeMap<String, String> appointments = new TreeMap<>();
        appointments.put("14:00", "Dentist");
        appointments.put("09:30", "Team stand-up");
        appointments.put("11:15", "Lunch with Ana");

        String first = appointments.firstKey();
        System.out.println("first slot: " + first + " (" + appointments.get(first) + ")");

        appointments.remove(first);
        System.out.println("after it is done: " + appointments.firstKey());
    }
}

How It Works

  1. Insertion order is irrelevant. "14:00" went in first, yet firstKey() answers "09:30", because the tree keeps the string keys sorted no matter when they arrived.
  2. Key first, value second. firstKey hands back only the time; a follow-up get(first) fetches the description "Team stand-up".
  3. The front moves on. Once the 09:30 slot is removed, the next call reports "11:15", the earliest of the two appointments still booked.

Example 2 — firstKey() Throws Where firstEntry() Returns null

An empty ticket queue shows the two ways the "lowest" methods report that there is nothing to return.

Java
import java.util.NoSuchElementException;
import java.util.TreeMap;

public class TreeMapFirstKeyEmpty {
    public static void main(String[] args) {
        TreeMap<Integer, String> queue = new TreeMap<>();

        System.out.println("firstEntry(): " + queue.firstEntry());
        try {
            System.out.println(queue.firstKey());
        } catch (NoSuchElementException e) {
            System.out.println("firstKey(): " + e.getClass().getSimpleName());
        }

        Integer safe = queue.isEmpty() ? null : queue.firstKey();
        System.out.println("guarded: " + safe);
    }
}

How It Works

  1. A quiet null. firstEntry() on the empty queue simply returns null, which prints as the word null.
  2. A loud failure. firstKey() has no key to return, so it throws NoSuchElementException and the println inside the try never runs.
  3. Guard, then ask. The conditional only calls firstKey() when isEmpty() is false, so safe ends up null without any exception.

Example 3 — "First" Means Largest in a Reversed Map

The same three report years go into a natural-order map and a reverse-order map.

Java
import java.util.Collections;
import java.util.TreeMap;

public class TreeMapFirstKeyReverse {
    public static void main(String[] args) {
        TreeMap<Integer, String> ascending = new TreeMap<>();
        TreeMap<Integer, String> descending = new TreeMap<>(Collections.reverseOrder());
        int[] years = {2019, 2024, 2021};
        for (int y : years) {
            ascending.put(y, "report " + y);
            descending.put(y, "report " + y);
        }
        System.out.println("natural firstKey: " + ascending.firstKey());
        System.out.println("reversed firstKey: " + descending.firstKey());
        System.out.println("reversed map: " + descending);
    }
}

How It Works

  1. Oldest year under natural order. Integer keys sort numerically, so the ascending map starts at 2019.
  2. Newest year once reversed. Collections.reverseOrder() puts 2024 at the front of descending, and firstKey() follows the comparator, not the size of the number.
  3. Printing confirms it. The reversed map lists 2024, 2021, 2019; firstKey() is always whatever key would be printed first.

Frequently Asked Questions

The lowest key according to the map's ordering: the smallest number or alphabetically first string under natural ordering, or the first key the comparator puts at the front.
It throws NoSuchElementException. Use firstEntry(), which returns null, or check isEmpty() before calling it.
No. It only reads the map. To read and remove the lowest entry in one step, use pollFirstEntry().
firstKey() returns only the key and throws on an empty map. firstEntry() returns an immutable key/value snapshot and returns null on an empty map.
O(log n). It walks down the left side of the red-black tree from the root to the leftmost node.

Next: floorEntry()

Get the pair with the largest key at or below a value.

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

12 people found this page helpful