Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java 21 LinkedHashMap.putFirst and putLast for explicit key order

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

LinkedHashMap.putFirst and putLast place a mapping at a chosen encounter-order endpoint, including when the key already exists.

Separate replacement from relocation

Ordinary put on an insertion-order LinkedHashMap replaces an existing value without making that key the newest entry. putFirst and putLast explicitly move an existing mapping to the requested endpoint. The return value is the previous value for that key, or null when no previous mapping existed. Null values complicate using that return as a presence signal; containsKey answers the separate presence question.

The fixture replaces a queued dispatch count while moving its key to the front, then moves another key to the back. Its output states both the value change and the final key order.

Use order as a contract

A HashMap has no encounter-order contract. If ordering is part of a response or processing policy, choose the ordered implementation deliberately. LinkedHashMap fundamentals cover insertion and access order; the reversed map view adds an inverse orientation in Java 21.

Mutating the map while another thread iterates requires a synchronization or ownership boundary. Endpoint placement does not make the map concurrent.

Working program

Java
import java.util.LinkedHashMap;

public class ReorderDispatchCounts {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> counts = new LinkedHashMap<>();
        counts.put("load-15", 1);
        counts.put("seal-47", 2);
        counts.put("ship-82", 3);
        System.out.println(counts.putFirst("ship-82", 4));
        counts.putLast("load-15", 1);
        System.out.println(counts.keySet());
        System.out.println(counts.get("ship-82"));
    }
}

Output

Output
3
[ship-82, seal-47, load-15]
4

Cost and ownership

Explicit endpoint placement is a map operation rather than a sort. LinkedHashMap lookup and update are expected constant-time under ordinary hash distribution, while full traversal is O(n). Keys and values are retained by reference.

Common Mistakes

  • Do not expect put on an insertion-order map to reposition an existing key.
  • Do not treat a null return as proof that the key was absent if null values are permitted.
  • Do not infer thread safety from a predictable encounter order.

Read next

Java LinkedHashMap: encounter order and a bounded cache model, linkedhashmap reversed view, linkedhashset endpoint relocation, Java 21 sequenced collections: endpoints and reversed views.

java
collections
linkedhashmap-explicit-position
Storage details