Sub topic 10
sequencedKeySet, sequencedValues and sequencedEntrySet
This chapter assumes you know Map, LinkedHashMap and TreeMap, and that you have read the earlier chapters on SequencedCollection, reversed views and SequencedMap. You need a Java 21 or newer JDK to run the examples.
Why the map needs sequenced views
A SequencedMap has a defined encounter order for its entries. The ordinary view methods keySet(), values() and entrySet() do not say so in their types. They return Set<K>, Collection<V> and Set<Map.Entry<K,V>>. If you want getFirst(), getLast() or reversed() on one of those views, the compiler does not offer it.
Java 21 adds three methods to SequencedMap that return the same views with sequenced types:
| Method | Return type | Elements |
|---|---|---|
| `sequencedKeySet()` | `SequencedSet<K>` | keys in the map's encounter order |
| `sequencedValues()` | `SequencedCollection<V>` | values, which may repeat, in the same order |
| `sequencedEntrySet()` | `SequencedSet<Map.Entry<K,V>>` | entries in the same order |
The names differ from the old methods because the old methods cannot change their return types without breaking existing code. In LinkedHashMap, the object returned by keySet() may already implement SequencedSet at run time. You cannot rely on that, because the static type is only Set. Call the new methods when you need the sequenced API.
The views fit together with the map like this:
Reading the ends and reversing
Each view supports the read operations from SequencedCollection: getFirst(), getLast() and reversed(). Streams and iterators then follow the map's order.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedCollection;
import java.util.SequencedMap;
import java.util.SequencedSet;
public class MapViews {
public static void main(String[] args) {
SequencedMap<String, Integer> stock = new LinkedHashMap<>();
stock.put("apple", 5);
stock.put("pear", 2);
stock.put("plum", 9);
SequencedSet<String> keys = stock.sequencedKeySet();
SequencedCollection<Integer> values = stock.sequencedValues();
SequencedSet<Map.Entry<String, Integer>> entries = stock.sequencedEntrySet();
System.out.println(keys.getFirst()); // apple
System.out.println(values.getLast()); // 9
System.out.println(entries.getFirst()); // apple=5
System.out.println(keys.reversed()); // [plum, pear, apple]
System.out.println(values.reversed()); // [9, 2, 5]
System.out.println(entries.reversed()); // [plum=9, pear=2, apple=5]
}
}Before Java 21, the last key of a LinkedHashMap needed a loop over keySet(), or a copy into a list. Now it is map.sequencedKeySet().getLast(). A common use is map.sequencedValues().reversed().stream(), which streams the values from newest to oldest insertion without copying anything.
Why use the entry view instead of firstEntry()
SequencedMap also has firstEntry() and lastEntry(). These return null when the map is empty. sequencedEntrySet().getFirst() throws NoSuchElementException in the same situation. Choose by how you want to handle emptiness:
- Use
firstEntry()when an empty map is a normal case and you want to test fornull. - Use
sequencedEntrySet().getFirst()when an empty map is a bug and you want it to fail loudly.
The views are live
None of the three views is a copy. Each one reads through to the map, and the supported writes go back to the map. This is the same live-view behavior you saw with reversed() on a list.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedCollection;
import java.util.SequencedMap;
import java.util.SequencedSet;
public class ViewWriteThrough {
public static void main(String[] args) {
SequencedMap<String, Integer> stock = new LinkedHashMap<>();
stock.put("apple", 5);
stock.put("pear", 2);
stock.put("plum", 9);
SequencedSet<String> keys = stock.sequencedKeySet();
SequencedCollection<Integer> values = stock.sequencedValues();
stock.put("fig", 1);
System.out.println(keys); // [apple, pear, plum, fig]
keys.removeFirst(); // removes the apple mapping from the map
System.out.println(stock); // {pear=2, plum=9, fig=1}
values.removeLast(); // removes the fig mapping from the map
System.out.println(stock); // {pear=2, plum=9}
for (Map.Entry<String, Integer> e : stock.sequencedEntrySet()) {
e.setValue(e.getValue() + 100);
}
System.out.println(stock); // {pear=102, plum=109}
Map.Entry<String, Integer> first = stock.firstEntry();
try {
first.setValue(0);
} catch (UnsupportedOperationException ex) {
System.out.println("firstEntry returns a snapshot");
}
}
}The program shows four behaviors:
- A
puton the map shows up in a view you created earlier. You do not need to callsequencedKeySet()again. - Removing through the key view or the value view removes the whole mapping from the map. Removing the last value removes the entry that holds it.
- Entries you obtain by iterating the entry view of a
LinkedHashMapsupportsetValue, and the change is written to the map. Changing a value is not a structural change, so it does not break the iteration. - The entry returned by
firstEntry()orlastEntry()is a snapshot. CallingsetValueon it throwsUnsupportedOperationException. If you need to update the first entry, useputwith its key.
Take a copy when you need a stable list
Because the views are live, they can change under you. If you want a fixed list of the keys as they are now, copy the view:
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SequencedMap;
public class KeySnapshot {
public static void main(String[] args) {
SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("a", 1);
m.put("b", 2);
List<String> snapshot = List.copyOf(m.sequencedKeySet());
m.put("c", 3);
System.out.println(snapshot); // [a, b]
System.out.println(m.sequencedKeySet()); // [a, b, c]
}
}What the views refuse to do
The views let you remove elements and read from either end. They do not let you add elements. This follows from what each view is:
- A key set has no value to attach to a new key.
- A value collection has no key to attach to a new value.
- An entry set could in principle accept a whole entry, but the map interfaces never allowed
addonentrySet(), and the sequenced version keeps that rule.
So addFirst and addLast on any of the three views throw UnsupportedOperationException. To insert at an end, call putFirst or putLast on the map itself.
Sorted maps add a second restriction. A TreeMap decides the position of each key from its comparator, so you cannot choose a position. putFirst and putLast throw UnsupportedOperationException on it. The read operations still work, and reversed() gives you the descending order.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SequencedMap;
import java.util.TreeMap;
public class ViewLimits {
public static void main(String[] args) {
SequencedMap<String, Integer> tree = new TreeMap<>(Map.of("b", 2, "a", 1, "c", 3));
System.out.println(tree.sequencedKeySet().getFirst()); // a
System.out.println(tree.sequencedValues().reversed()); // [3, 2, 1]
try {
tree.sequencedKeySet().addFirst("z");
} catch (UnsupportedOperationException e) {
System.out.println("views do not accept additions");
}
try {
tree.putFirst("z", 0);
} catch (UnsupportedOperationException e) {
System.out.println("TreeMap decides the position itself");
}
SequencedMap<String, Integer> empty = new LinkedHashMap<>();
System.out.println(empty.firstEntry()); // null
try {
empty.sequencedKeySet().getFirst();
} catch (NoSuchElementException e) {
System.out.println("getFirst on an empty view throws");
}
}
}The TreeMap values come out as [3, 2, 1] because reversed() on the value view follows the reversed key order: the values for c, b and a.
Summary of failure modes
| Call | Where | Result |
|---|---|---|
| `addFirst` or `addLast` | any of the three views | `UnsupportedOperationException` |
| `putFirst` or `putLast` | `TreeMap` | `UnsupportedOperationException` |
| `getFirst`, `getLast`, `removeFirst`, `removeLast` | empty view | `NoSuchElementException` |
| `firstEntry`, `lastEntry` | empty map | returns `null` |
| `setValue` | entry from `firstEntry()` | `UnsupportedOperationException` |
| any removal | view of an unmodifiable map | `UnsupportedOperationException` |
Common errors
Several mistakes come up often when people first use these views.
- Calling
keySet().getFirst(). The static type isSet, which has nogetFirst, so this does not compile. UsesequencedKeySet(). - Expecting a
HashMapto have these views.HashMapis not aSequencedMap, and neither are the maps fromMap.of. The method does not exist on them. If you need it, change the declared type toSequencedMapand use aLinkedHashMap. - Modifying the map while looping over a view. Putting a new key or removing a key during a
forloop over a view throwsConcurrentModificationException, as it does withkeySet(). Remove through the view's own iterator, or copy first. - Assuming a view is a snapshot. A list you built from
values()last week is a copy. ASequencedCollectionyou got fromsequencedValues()is not. - Treating
sequencedValues()as a set. Two keys can have equal values, so the value view can hold duplicates. Callingremove(value)on it removes only the first matching mapping in encounter order.
Parameter types
When a method only reads the order, accept the narrowest sequenced type that you need. A method that prints the newest value does not need a map:
import java.util.LinkedHashMap;
import java.util.SequencedCollection;
import java.util.SequencedMap;
public class Newest {
static <T> T newest(SequencedCollection<T> items) {
return items.getLast();
}
public static void main(String[] args) {
SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("x", 10);
m.put("y", 20);
System.out.println(newest(m.sequencedValues())); // 20
System.out.println(newest(m.sequencedKeySet())); // y
}
}The same method also accepts an ArrayList or an ArrayDeque, since both are SequencedCollections. For the map case, the views give you one code path for keys, values and entries.
Choosing between the access paths
Use this guide when you read or change an end of a SequencedMap:
- To read the first or last entry and handle emptiness with
null, usefirstEntry()orlastEntry(). - To read the first or last key, value or entry and treat emptiness as an error, use the matching sequenced view with
getFirst()orgetLast(). - To remove and return an end entry, use
pollFirstEntry()orpollLastEntry(). They returnnullon an empty map. - To remove an end without using the returned entry, use the view's
removeFirst()orremoveLast(). They throw when empty. - To iterate in reverse, use
reversed()on the map or on a view. Pick the one that matches the elements you want. - To insert at a chosen end, use
putFirstorputLaston aLinkedHashMap. Never use a view for this.
Exercise
A LinkedHashMap<String, Integer> named scores holds {ann=3, bob=7, cy=5}. Without running the code, what do scores.sequencedKeySet().reversed() and scores.sequencedValues().reversed() print? Then say what happens when you call scores.sequencedKeySet().addLast("dee").
Show answer
The key view prints [cy, bob, ann] and the value view prints [5, 7, 3]. Both follow the map's encounter order backwards. Calling addLast("dee") on the key view throws UnsupportedOperationException, because a key cannot be added without a value. To add the key at the end, call scores.putLast("dee", 0) or scores.put("dee", 0).
Exercise
You write List<String> names = new ArrayList<>(map.sequencedKeySet()); and later call map.put("new", 1). Does names contain "new"? Then write one line that removes the oldest mapping from a LinkedHashMap named cache and returns its key, or null when the cache is empty.
Show answer
No. The constructor copies the elements at that moment, so names is not a view and does not change when the map changes. One possible line is: var oldest = cache.pollFirstEntry(); String key = oldest == null ? null : oldest.getKey(); This works because pollFirstEntry() removes and returns the first entry, or returns null when the map is empty.