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

Java 21 SequencedMap.reversed: edits through a reverse-ordered map view

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

A reversed SequencedMap view exposes the opposite encounter order and writes supported changes into the backing map.

Translate the operation

On a LinkedHashMap, putFirst through the reversed view places a mapping at the backing map's last endpoint. pollLastEntry through the view removes the backing map's first mapping. The view is not a detached map and does not duplicate key or value objects.

Use the returned entry from pollLastEntry only after checking whether the map was empty. It returns null on an empty map. This fixture starts nonempty and prints the removed key to make the orientation visible.

Avoid accidental access-order changes

This program uses insertion order. An access-order LinkedHashMap has a different movement policy, and some reads can reorder it. When order drives eviction or display, specify which policy is in force and test it separately. Explicit positioning gives a narrower contract when the application chooses the endpoint.

Reversed view iterators still traverse a mutable map. Concurrent structural changes need an ownership rule; fail-fast observation is not a lock.

Working program

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

public class ReverseDispatchMap {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> counts = new LinkedHashMap<>();
        counts.put("load-15", 1);
        counts.put("seal-47", 2);
        SequencedMap<String, Integer> reverse = counts.reversed();
        reverse.putFirst("ship-82", 3);
        System.out.println(counts.keySet());
        System.out.println(reverse.sequencedKeySet());
        Map.Entry<String, Integer> removed = reverse.pollLastEntry();
        System.out.println(removed.getKey());
        System.out.println(counts.keySet());
    }
}

Output

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

Cost and ownership

The reversed map is a view, so construction does not copy n mappings. Encounter-order traversal is O(n). Endpoint edits propagate to the backing LinkedHashMap; the view and original require the same mutation discipline.

Common Mistakes

  • Do not call reversed a defensive copy.
  • Do not read pollLastEntry on a reversed view as removal of the backing tail.
  • Do not dereference an empty-map poll result without checking for null.

Read next

Java 21 LinkedHashMap.putFirst and putLast for explicit key order, Java LinkedHashMap: encounter order and a bounded cache model, Java 21 sequenced collections: endpoints and reversed views, collections unmodifiable live view.

java
collections
linkedhashmap-reversed-view
Storage details