Java TreeMap putFirst() Method

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

Definition

In Java 21, putFirst(key, value) was added by the new SequencedMap interface: on maps with a user-controlled order, it inserts a mapping (or moves an existing one) to the front. TreeMap is a SequencedMap too, but on a TreeMap this method always throws UnsupportedOperationException.

The reason is simple: in a sorted map, the comparator alone decides which key comes first. Letting you pick a position would break the sorting rule, so the call is rejected even when the key would sort first anyway. Use put() and let the order take care of itself.

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

The call compiles on Java 21+, but on a TreeMap it can only throw.

Java
TreeMap<String, Integer> queue = new TreeMap<>();
queue.putFirst("bob", 2);   // throws UnsupportedOperationException
queue.put("bob", 2);        // the TreeMap way: stored in sorted position
CallWhat it does
treeMap.putFirst(k, v)Always throws UnsupportedOperationException.
linkedHashMap.putFirst(k, v)Works: inserts or moves the mapping to the front (Java 21+).
treeMap.put(k, v)Stores the mapping where the comparator puts it.
treeMap.firstEntry()Reads whatever entry currently sorts first.

Views of a TreeMap such as descendingMap(), headMap(), or the Java 21 reversed() are sorted too, so their putFirst throws as well.

Library declarations
Java
// java.util.TreeMap<K, V>  (Java 21+)
public V putFirst(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. Ignored: the call throws before using it.
v (V)The value. Ignored as well.

Return Value

Return ValueDescription
VDeclared to return the previous value, but on a TreeMap it never returns normally.
throws UnsupportedOperationExceptionAlways, and the map is left unchanged.

Compare with Similar Methods

Getting something "first" in a map:

MethodHow it differs
put(k, v)The supported way to add to a TreeMap.
firstEntry()Reads the entry that sorts first.
putLast(k, v)The Java 21 twin; also always throws on a TreeMap.
descendingMap()Flip the order so the largest key comes first.

Java Examples

Example 1 — Try putFirst and Fall Back to put

Java 21: the call throws, the map stays the same, and put stores the entry in sorted position.

Java
import java.util.TreeMap;

public class TreeMapPutFirstRejected {
    public static void main(String[] args) {
        TreeMap<String, Integer> queue = new TreeMap<>();
        queue.put("carol", 3);
        queue.put("alice", 1);

        try {
            queue.putFirst("bob", 2);
        } catch (UnsupportedOperationException e) {
            System.out.println("putFirst: " + e.getClass().getSimpleName());
        }
        System.out.println("unchanged: " + queue);
        queue.put("bob", 2);
        System.out.println("after put: " + queue);
    }
}

How It Works

  1. Compiles, then throws. On Java 21 TreeMap has a putFirst method, but its whole body is "throw UnsupportedOperationException".
  2. Nothing half-added. The second line shows only alice and carol, so the failed call left no trace.
  3. put chooses the slot. With plain put, bob lands between alice and carol: the position comes from the alphabet, not from the method name.

Example 2 — One SequencedMap Call, Two Different Maps

Java 21: the same helper method calls putFirst on a LinkedHashMap and on a TreeMap.

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

public class TreeMapPutFirstSequenced {
    static void tryPutFirst(String label, SequencedMap<String, Integer> map) {
        map.put("m", 2);
        map.put("z", 3);
        try {
            map.putFirst("q", 1);
            System.out.println(label + ": " + map);
        } catch (UnsupportedOperationException e) {
            System.out.println(label + ": putFirst not supported, map is " + map);
        }
    }

    public static void main(String[] args) {
        tryPutFirst("LinkedHashMap", new LinkedHashMap<>());
        tryPutFirst("TreeMap", new TreeMap<>());
    }
}

How It Works

  1. One interface, two answers. Both classes are SequencedMaps in Java 21, so the helper compiles for either map.
  2. LinkedHashMap obeys. Its order is the order you build, so q is placed in front of m and z even though q is not the smallest letter.
  3. TreeMap refuses. Its order is fixed by sorting, so the same call throws and the map keeps just m and z.

Example 3 — Make the Newest Year Come First With a Comparator

Java 21: instead of putFirst, pick an ordering where the entry you want naturally sorts first, and use reversed() for the other direction.

Java
import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapPutFirstByComparator {
    public static void main(String[] args) {
        TreeMap<Integer, String> news = new TreeMap<>(Comparator.reverseOrder());
        news.put(2024, "launch");
        news.put(2025, "update");
        news.put(2026, "redesign");

        System.out.println("first entry: " + news.firstEntry());
        System.out.println("oldest first: " + news.reversed());
    }
}

How It Works

  1. Order chosen up front. Comparator.reverseOrder() makes larger years sort first, so each newer year automatically becomes the first entry.
  2. firstEntry confirms it. The entry at the front is 2026=redesign, the last one added, with no positioning call needed.
  3. reversed() is a view. Java 21's reversed() on a TreeMap returns descendingMap(), showing the same entries oldest first without copying.

Frequently Asked Questions

A TreeMap orders keys with its comparator, so it cannot place a key at a position you choose. Java 21 documents that TreeMap always throws for putFirst and putLast.
Java 21, through the SequencedMap interface (JEP 431). On older versions the method does not exist at all.
Yes. The method never inspects the key; it throws in every case and leaves the map unchanged.
LinkedHashMap supports it: the mapping is inserted or moved to the front. Sorted maps such as TreeMap and ConcurrentSkipListMap reject it.
Choose the ordering: use a Comparator under which that key is smallest, or read the map in reverse with descendingMap() or reversed().

Next: putIfAbsent()

Add a value only when the key is missing (or null).

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