Sub topic 6
SequencedMap and LinkedHashMap
This chapter assumes you know Map, HashMap, LinkedHashMap and TreeMap. It also assumes you have read the earlier chapters on encounter order, SequencedCollection and reversed views. You need a Java 21 or newer JDK to run the code.
The problem with maps before Java 21
A LinkedHashMap has always remembered the order in which keys were inserted. The Map interface gave you no direct way to use that order.
- To get the first entry, you wrote
map.entrySet().iterator().next(). This throwsNoSuchElementExceptionon an empty map. - To get the last entry, you had to iterate through every entry and keep the final one. The cost grows with the size of the map.
- To iterate in reverse, you copied the entries into a list and reversed it. The copy was a snapshot and went stale as soon as the map changed.
TreeMapofferedfirstEntry()andlastEntry()throughNavigableMap, butLinkedHashMapoffered nothing comparable.
SequencedMap<K,V> closes this gap. It is the map counterpart of SequencedCollection: a map whose entries have a defined encounter order, with one API for both ends.
The SequencedMap API
SequencedMap extends Map. It adds these methods.
| Method | Purpose | Empty map |
|---|---|---|
| `firstEntry()` | Returns the first entry | Returns `null` |
| `lastEntry()` | Returns the last entry | Returns `null` |
| `pollFirstEntry()` | Removes and returns the first entry | Returns `null` |
| `pollLastEntry()` | Removes and returns the last entry | Returns `null` |
| `putFirst(K, V)` | Puts a mapping at the front | n/a |
| `putLast(K, V)` | Puts a mapping at the end | n/a |
| `reversed()` | Returns a live reverse-order view | Returns an empty view |
| `sequencedKeySet()` | Returns the keys as a `SequencedSet<K>` | Returns an empty view |
| `sequencedValues()` | Returns the values as a `SequencedCollection<V>` | Returns an empty view |
| `sequencedEntrySet()` | Returns the entries as a `SequencedSet<Map.Entry<K,V>>` | Returns an empty view |
SequencedMap has no getFirst() or getLast(). It follows the NavigableMap naming style (firstEntry, pollFirstEntry) instead of the List style. It also returns null for an empty map, where SequencedCollection.getFirst() throws. Code that moves between the two APIs needs to handle both behaviours.
Basic use
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class MapEnds {
public static void main(String[] args) {
SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("one", 1);
m.put("two", 2);
m.putFirst("zero", 0);
System.out.println(m); // {zero=0, one=1, two=2}
System.out.println(m.firstEntry()); // zero=0
System.out.println(m.lastEntry()); // two=2
System.out.println(m.reversed()); // {two=2, one=1, zero=0}
System.out.println(m.pollLastEntry()); // two=2
System.out.println(m); // {zero=0, one=1}
}
}The variable is typed as SequencedMap, not LinkedHashMap. That is the pattern to prefer. Only the constructor call names the concrete class.
Entries returned by the end operations are snapshots
firstEntry(), lastEntry(), pollFirstEntry() and pollLastEntry() return entries that you cannot modify. Calling setValue on one throws UnsupportedOperationException. The entry also does not track later changes to the map.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedMap;
public class SnapshotEntry {
public static void main(String[] args) {
SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("a", 1);
m.put("b", 2);
Map.Entry<String, Integer> first = m.firstEntry();
try {
first.setValue(99);
} catch (UnsupportedOperationException e) {
System.out.println("entry is read-only");
}
m.put("a", 100);
System.out.println(first.getValue()); // 1, the snapshot does not change
System.out.println(m.get("a")); // 100
SequencedMap<String, Integer> empty = new LinkedHashMap<>();
System.out.println(empty.firstEntry()); // null
System.out.println(empty.pollLastEntry()); // null
}
}To update the value of the first entry, call m.put(first.getKey(), newValue). For a LinkedHashMap this keeps the entry in its current position.
Repositioning with putFirst and putLast
On a plain Map, put for an existing key replaces the value and leaves the key where it was. LinkedHashMap.putFirst and putLast are different. If the key is already present, they move its entry to the requested end and replace the value. Both methods return the previous value for the key, or null if there was none. This is the same return convention as put.
import java.util.LinkedHashMap;
public class MapReposition {
public static void main(String[] args) {
LinkedHashMap<String, Integer> m = new LinkedHashMap<>();
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
System.out.println(m.putFirst("c", 30)); // 3
System.out.println(m); // {c=30, a=1, b=2}
System.out.println(m.putLast("a", 10)); // 1
System.out.println(m); // {c=30, b=2, a=10}
m.put("c", 31); // plain put keeps the position
System.out.println(m); // {c=31, b=2, a=10}
}
}These two methods let you build a "move to front" or "most recently used last" structure without removing and re-inserting the key yourself.
A LinkedHashMap can also be created in access order with new LinkedHashMap<>(16, 0.75f, true). Each get then moves the entry to the end. This is the standard basis for an LRU cache. The least recently used entry is at the front, so pollFirstEntry() evicts it. In this mode get changes the order, so it counts as a structural modification. Do not call it while iterating.
Reversed views write through
reversed() does not copy anything. It returns a view of the same entries in the opposite order. Changes made through the view appear in the original map, and the reverse is also true. The mirrored positions follow from this:
putFirston the view acts likeputLaston the original.firstEntryon the view returns the original'slastEntry.pollLastEntryon the view removes the original's first entry.
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class ReversedMapView {
public static void main(String[] args) {
SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
SequencedMap<String, Integer> rev = m.reversed();
rev.putFirst("z", 26); // front of the view is the end of the original
System.out.println(m); // {a=1, b=2, c=3, z=26}
System.out.println(rev); // {z=26, c=3, b=2, a=1}
m.remove("a"); // change the original
System.out.println(rev); // {z=26, c=3, b=2}
System.out.println(rev.firstEntry()); // z=26
System.out.println(rev.reversed()); // {b=2, c=3, z=26}
}
}Reversing a reversed view gives you a view of the original order again. The JDK does not stack two layers of reversal.
The sequenced views
Map already has keySet(), values() and entrySet(). SequencedMap adds sequencedKeySet(), sequencedValues() and sequencedEntrySet(). They return the same data as live views, typed with the sequenced interfaces. You can then call getFirst(), getLast() and reversed() on them.
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class MapViews {
public static void main(String[] args) {
SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("x", 10);
m.put("y", 20);
m.put("z", 30);
System.out.println(m.sequencedKeySet().getLast()); // z
System.out.println(m.sequencedValues().reversed()); // [30, 20, 10]
System.out.println(m.sequencedEntrySet().getFirst()); // x=10
m.sequencedKeySet().removeFirst(); // removes the mapping for x
System.out.println(m); // {y=20, z=30}
try {
m.sequencedKeySet().addFirst("w"); // key views cannot add
} catch (UnsupportedOperationException e) {
System.out.println("cannot add through a key view");
}
}
}These views follow the same rule as keySet() and values(). You can remove through them, which removes the mapping from the map. You cannot add through them, because a key has no value attached. Here getFirst() and getLast() come from SequencedCollection, so on an empty view they throw NoSuchElementException.
Where SequencedMap sits in the hierarchy
The JDK retrofitted SequencedMap into the existing map types. SortedMap now extends SequencedMap, so TreeMap and ConcurrentSkipListMap are sequenced maps. HashMap and Map.of(...) results are not, because their iteration order is not defined as part of a contract.
LinkedHashMap implements SequencedMap directly, so any code that already used it can adopt the new interface. Note that LinkedHashMap extends HashMap, but HashMap itself is not sequenced. Do not declare a parameter as HashMap and expect ordered behaviour.
Exceptions and edge cases
The sorted maps support the read operations but not the positional writes. The comparator, not the caller, decides where a key goes.
import java.util.Map;
import java.util.TreeMap;
public class SortedMapEdges {
public static void main(String[] args) {
TreeMap<String, Integer> tree = new TreeMap<>(Map.of("b", 2, "a", 1, "c", 3));
System.out.println(tree.firstEntry()); // a=1
System.out.println(tree.reversed()); // {c=3, b=2, a=1}
try {
tree.putFirst("0", 0);
} catch (UnsupportedOperationException e) {
System.out.println("putFirst is unsupported on sorted maps");
}
System.out.println(tree.reversed().firstKey()); // c
}
}The behaviours to remember:
putFirstandputLastthrowUnsupportedOperationExceptiononTreeMapand other sorted maps. The default implementations inSequencedMapalso throw it, so a custom implementation must override them to support writes.firstEntry(),lastEntry()and the poll methods returnnullon an empty map. ThegetFirst/getLastcalls on the sequenced views throwNoSuchElementException.- A reversed view of a
TreeMapis still sorted, using the reversed comparator. It is aNavigableMap, so calls such asfirstKey()work on it. - Unmodifiable maps reject all writes, including
pollFirstEntry. The next section covers how to create one.
Read-only sequenced wrappers
Collections.unmodifiableSequencedMap(map) returns a read-only SequencedMap view. It keeps the order and the reversed view, but every write throws UnsupportedOperationException. It is a view, not a copy. Changes made to the underlying map remain visible through it. Copy first with new LinkedHashMap<>(map) if you need a snapshot.
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class ReadOnlyMap {
public static void main(String[] args) {
SequencedMap<String, Integer> backing = new LinkedHashMap<>();
backing.put("a", 1);
SequencedMap<String, Integer> ro = Collections.unmodifiableSequencedMap(backing);
backing.put("b", 2);
System.out.println(ro.lastEntry()); // b=2, the view tracks the original
try {
ro.pollFirstEntry();
} catch (UnsupportedOperationException e) {
System.out.println("read-only");
}
}
}Map.copyOf and Map.of return immutable maps that are not sequenced. Their iteration order is unspecified, so there is no immutable sequenced map factory beyond this wrapper.
Adopting SequencedMap in existing code
Follow these steps when you migrate.
- Change parameter and return types from
LinkedHashMaptoSequencedMapwhen callers only need order-aware operations. This acceptsTreeMapas well. - Replace
map.entrySet().iterator().next()withfirstEntry(). Check fornullinstead of catchingNoSuchElementException. - Replace "copy into a list and reverse" with
reversed(). Copy only when you need a snapshot that is independent of later changes. - Check for name clashes. If your own class extends
LinkedHashMapand already declares methods namedputFirst,putLast,reversedorfirstEntrywith different return types, it will not compile on Java 21. The same applies to classes that implementMapandDeque-like interfaces together. - If you use
Map.Entryresults fromfirstEntry(), do not callsetValue. Useputinstead.
import java.util.Map;
import java.util.SequencedMap;
public class Reports {
static String newest(SequencedMap<String, Integer> log) {
Map.Entry<String, Integer> e = log.lastEntry();
return e == null ? "none" : e.getKey() + "=" + e.getValue();
}
}This method works for a LinkedHashMap of events in insertion order and for a TreeMap keyed by timestamp.
Exercise
A LinkedHashMap holds a=1, b=2, c=3 in that order. You call rev.putLast("a", 9) on rev = map.reversed(). What does the original map contain afterwards, and what does the call return?
Show answer
The original map is {b=2, c=3, a=9}... wait, check the direction: the end of the reversed view is the front of the original, so "a" moves to the front. The original becomes {a=9, b=2, c=3}, and the call returns 1, the previous value for "a".
Exercise
Why does new TreeMap<String,Integer>().putFirst("k", 1) throw, while new TreeMap<String,Integer>().firstEntry() returns null without throwing?
Show answer
A sorted map decides entry positions with its comparator, so a caller cannot choose the front. putFirst therefore throws UnsupportedOperationException. firstEntry() is a read on an empty map, and the entry methods return null for an empty map.