Java TreeMap lastKey() Method

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

Definition

In Java, lastKey() returns the highest key in a TreeMap, the one that comes last in the map's sort order. The map is not changed.

It is the mirror image of firstKey(): the lookup follows right children from the root, so it takes O(log n) time. Called on a range view, it returns the highest key inside that range, which makes "latest value before a cutoff" a one-liner.

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

Call it with no arguments to get the maximum key.

Java
TreeMap<Integer, String> builds = new TreeMap<>();
builds.put(3, "Lime");
builds.put(12, "Mango");
int latest = builds.lastKey();   // 12
CallWhat it does
map.lastKey()The highest key; throws when the map is empty.
map.lastEntry()The highest key with its value, or null.
map.headMap(k).lastKey()The highest key strictly below k.

lastKey() is the largest key by the comparator. String keys such as "12" and "7" compare character by character, so "7" would be last; store numbers as Integer when you want numeric order.

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

// Declared in SortedMap<K, V>

Parameters

ParameterDescription
(none)lastKey takes no parameters.

Return Value

Return ValueDescription
KThe last (highest) key according to the map's ordering.

Compare with Similar Methods

Ways to reach the high end of a TreeMap:

MethodHow it differs
lastEntry()Key and value as a snapshot; null when empty.
firstKey()The lowest key instead of the highest.
pollLastEntry()Reads and removes the highest entry.
floorKey(k)The highest key that is at most k.

Java Examples

Example 1 — Report the Newest Release

Build numbers are Integer keys, so 12 counts as newer than 7 even though "12" < "7" as text.

Java
import java.util.TreeMap;

public class TreeMapLastKeyVersions {
    public static void main(String[] args) {
        TreeMap<Integer, String> releases = new TreeMap<>();
        releases.put(3, "Lime");
        releases.put(12, "Mango");
        releases.put(7, "Kiwi");

        int latest = releases.lastKey();
        System.out.println("latest build: " + latest + " " + releases.get(latest));

        releases.put(15, "Nectarine");
        System.out.println("after a new release: " + releases.lastKey());
    }
}

How It Works

  1. Numeric maximum. Among 3, 12, and 7 the tree's rightmost key is 12, so the newest build is Mango.
  2. Unboxing is safe. Assigning the result to an int cannot fail with a null, because a non-empty map always has a last key.
  3. New maximum, new answer. Adding build 15 changes the right end of the tree, and the second call reports 15 at once.

Example 2 — The Last Reading Before Noon

headMap(12) keeps only the hours before 12, so its lastKey() is the latest morning reading.

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

public class TreeMapLastKeyHeadView {
    public static void main(String[] args) {
        TreeMap<Integer, Double> readings = new TreeMap<>();
        readings.put(6, 11.5);
        readings.put(9, 14.0);
        readings.put(12, 18.25);
        readings.put(15, 17.5);

        SortedMap<Integer, Double> morning = readings.headMap(12);
        System.out.println("morning hours: " + morning.keySet());
        System.out.println("last morning reading at " + morning.lastKey() + ": " + readings.get(morning.lastKey()));
        try {
            readings.headMap(6).lastKey();
        } catch (NoSuchElementException e) {
            System.out.println("before 6: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Noon is left out. headMap(12) is exclusive, so the view holds hours 6 and 9 but not 12.
  2. Highest inside the window. The view's lastKey() is 9, and the reading 14.0 is fetched from the full map with that key.
  3. An empty window still throws. No hour lies below 6, so headMap(6) is empty and its lastKey() raises NoSuchElementException.

Example 3 — Hand Out the Next Invoice Number

The next id is lastKey() + 1, with a starting value for an empty book.

Java
import java.util.TreeMap;

public class TreeMapLastKeyNextId {
    static int nextId(TreeMap<Integer, String> invoices) {
        return invoices.isEmpty() ? 1001 : invoices.lastKey() + 1;
    }

    public static void main(String[] args) {
        TreeMap<Integer, String> invoices = new TreeMap<>();
        System.out.println("empty book, next id: " + nextId(invoices));

        invoices.put(nextId(invoices), "Garden chairs");
        invoices.put(nextId(invoices), "Paint");
        invoices.put(nextId(invoices), "Ladder");
        System.out.println(invoices);

        invoices.remove(1003);
        System.out.println("after removing 1003, next id: " + nextId(invoices));
    }
}

How It Works

  1. No crash on the first invoice. isEmpty() is checked before lastKey(), so the empty book returns the starting number 1001 instead of throwing.
  2. Each id builds on the last. Every put raises the maximum by one, producing 1001, 1002, and 1003.
  3. Watch for reuse. Deleting the top invoice lowers lastKey() to 1002, so 1003 would be issued a second time; keep a separate counter if numbers must never repeat.

Frequently Asked Questions

The highest key according to the map's ordering, for example the largest Integer or the alphabetically last String under natural ordering.
The map (or the view you called it on) has no keys. Use lastEntry(), which returns null, or check isEmpty() first.
Call lastEntry().getValue(), or get(map.lastKey()). Both read the value without changing the map.
Yes: headMap(limit).lastKey() returns the highest key strictly below limit. lowerKey(limit) does the same but returns null instead of throwing when there is none.
No. TreeMap does not remember insertion order; lastKey() is the largest key by sorting. Use LinkedHashMap if you need insertion order.

Next: lowerEntry()

Get the pair with the previous key strictly below a value.

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

15 people found this page helpful