Java TreeMap putLast() Method

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

Definition

putLast(key, value) is the second positioning method that Java 21's SequencedMap interface introduced. On an insertion-ordered map it puts the mapping at the end (moving it there if the key exists). A TreeMap implements the interface but always throws UnsupportedOperationException from putLast.

A key's place in a TreeMap follows from comparing it with the other keys, so "put this last" is a request the map cannot honour. To make an entry last, give it a key that sorts last (for example the next number) and call put().

An instance method of java.util.TreeMap, added in Java 21 by the SequencedMap 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. Requires Java 21 or newer.

Syntax

Valid Java 21 code that always ends in an exception on a TreeMap.

Java
TreeMap<Integer, String> log = new TreeMap<>();
log.putLast(3, "logout");   // throws UnsupportedOperationException
log.put(3, "logout");       // works; 3 sorts after 1 and 2
CallWhat it does
treeMap.putLast(k, v)Always throws UnsupportedOperationException.
treeMap.reversed().putLast(k, v)The reversed view is sorted too, so it throws as well.
linkedHashMap.putLast(k, v)Works: inserts or moves the mapping to the end.
treeMap.lastEntry()Reads the entry that currently sorts last.

putLast and putFirst() are the only SequencedMap methods a TreeMap rejects; firstEntry, lastEntry, pollFirstEntry, pollLastEntry, and reversed all work.

Library declarations
Java
// java.util.TreeMap<K, V>  (Java 21+)
public V putLast(K k, V v)   // always throws UnsupportedOperationException

// Declared in SequencedMap<K, V> (Java 21); SortedMap and TreeMap reject it

Parameters

ParameterDescription
k (K)The key. Not used: the method throws first.
v (V)The value. Not used either.

Return Value

Return ValueDescription
VThe declared type; a TreeMap never returns from this call.
throws UnsupportedOperationExceptionEvery time; no mapping is added or moved.

Compare with Similar Methods

Ways to end up with a "last" entry:

MethodHow it differs
put(k, v)Adds the mapping; it is last if its key is the largest.
lastEntry()Reads the entry that sorts last.
putFirst(k, v)The Java 21 twin; also unsupported on a TreeMap.
pollLastEntry()Removes and returns the last entry.

Java Examples

Example 1 — Append a Log Line With the Next Number

Java 21: putLast is rejected, but lastKey() + 1 with put lands at the end every time.

Java
import java.util.TreeMap;

public class TreeMapPutLastLog {
    public static void main(String[] args) {
        TreeMap<Integer, String> log = new TreeMap<>();
        log.put(1, "boot");
        log.put(2, "login");

        int next = log.lastKey() + 1;
        try {
            log.putLast(next, "logout");
        } catch (UnsupportedOperationException e) {
            System.out.println("putLast(" + next + ") -> " + e.getClass().getSimpleName());
        }
        log.put(next, "logout");
        System.out.println(log);
        System.out.println("last entry: " + log.lastEntry());
    }
}

How It Works

  1. Next number first. lastKey() is 2, so next is 3, a key that would sort last anyway.
  2. Rejected regardless. putLast(3, ...) still throws: the method does not check whether the position would be correct.
  3. put reaches the end. Because 3 is the largest key, put stores it after 1 and 2, and lastEntry() returns 3=logout.

Example 2 — The reversed() View Rejects putLast Too

Java 21: reversed() gives a live descending view. Positioning is refused, but a normal put goes through to the original map.

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

public class TreeMapPutLastReversed {
    public static void main(String[] args) {
        TreeMap<String, Integer> levels = new TreeMap<>();
        levels.put("gold", 3);
        levels.put("bronze", 1);

        NavigableMap<String, Integer> rev = levels.reversed();
        try {
            rev.putLast("silver", 2);
        } catch (UnsupportedOperationException e) {
            System.out.println("reversed().putLast: " + e.getClass().getSimpleName());
        }
        rev.put("silver", 2);
        System.out.println("reversed view: " + rev);
        System.out.println("original map:  " + levels);
    }
}

How It Works

  1. Still a sorted map. levels.reversed() is the same as descendingMap(): sorted, just backwards, so putLast on it throws.
  2. put through the view. rev.put("silver", 2) is allowed and writes into levels, because the view has no storage of its own.
  3. One map, two directions. The view prints silver, gold, bronze (Z to A), the original bronze, gold, silver (A to Z).

Example 3 — Copy Into a LinkedHashMap for a Hand-Made Order

Java 21: keep the sorted TreeMap, and build a shopping order in a LinkedHashMap where putLast and putFirst work.

Java
import java.util.LinkedHashMap;
import java.util.TreeMap;

public class TreeMapPutLastLinkedCopy {
    public static void main(String[] args) {
        TreeMap<String, Integer> sorted = new TreeMap<>();
        sorted.put("pasta", 9);
        sorted.put("bread", 3);
        sorted.put("milk", 2);

        LinkedHashMap<String, Integer> shoppingOrder = new LinkedHashMap<>(sorted);
        shoppingOrder.putLast("bread", 4);
        shoppingOrder.putFirst("pasta", 9);

        System.out.println("sorted:   " + sorted);
        System.out.println("my order: " + shoppingOrder);
    }
}

How It Works

  1. The copy starts sorted. new LinkedHashMap<>(sorted) takes the entries in the TreeMap's order: bread, milk, pasta.
  2. putLast moves and updates. bread already exists, so the LinkedHashMap moves it to the end and stores the new value 4.
  3. The source stays sorted. pasta is moved to the front of the copy only; the TreeMap still prints bread=3 first.

Frequently Asked Questions

The comparator decides where each key goes, so a TreeMap cannot put a mapping at the end on request. Java 21 specifies UnsupportedOperationException for it.
Give it a key that sorts after all others, such as lastKey() + 1 for numbers, and call put().
No. reversed() returns the descending view, which is also sorted and also rejects putLast and putFirst.
It inserts the mapping, or replaces the value and moves an existing key, so that it becomes the last entry in the map's order.
Yes. SequencedMap and its putFirst and putLast methods were added in Java 21; earlier versions will not compile the call.

Next: remove()

Delete a key and get its old value back.

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

8 people found this page helpful