Sub topic 9
Repositioning Elements with `addFirst`, `addLast`, `putFirst` and `putLast`
This chapter assumes that you know List, Set, Map, Deque, generics, and the difference between ordered and sorted collections. The examples require Java 21 or newer.
Java 21 lets some ordered collections change where an element appears without removing it manually and rebuilding the collection. addFirst and addLast apply to sequenced collections and sets. putFirst and putLast apply to sequenced maps.
Moving elements in a sequenced set
A LinkedHashSet has a defined encounter order. Its elements are unique, but their order is preserved. Java 21 adds methods that can place an element at either end.
If the element is new, the method inserts it. If the element already exists, the method moves it:
import java.util.LinkedHashSet;
import java.util.List;
public class SetReposition {
public static void main(String[] args) {
LinkedHashSet<String> set =
new LinkedHashSet<>(List.of("a", "b", "c"));
set.addFirst("c");
System.out.println(set); // [c, a, b]
set.addLast("a");
System.out.println(set); // [c, b, a]
set.addFirst("x");
System.out.println(set); // [x, c, b, a]
}
}The first call moves c from the end to the beginning. The second moves a from the beginning to the end. Calling ordinary add with an existing element does not reposition it.
This behavior is useful for ordered sets that represent priorities, recently used items, or processing queues.
Moving entries in a sequenced map
A SequencedMap has an encounter order for its entries. LinkedHashMap is the usual implementation.
Use putFirst or putLast to insert an entry at an end or reposition an existing key. The value is updated when the key already exists.
import java.util.LinkedHashMap;
import java.util.SequencedMap;
public class MapReposition {
public static void main(String[] args) {
SequencedMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("alice", 10);
scores.put("bob", 20);
scores.put("cara", 30);
scores.putFirst("cara", 35);
System.out.println(scores); // {cara=35, alice=10, bob=20}
scores.putLast("alice", 15);
System.out.println(scores); // {cara=35, bob=20, alice=15}
scores.putFirst("dina", 40);
System.out.println(scores); // {dina=40, cara=35, bob=20, alice=15}
}
}The key identifies the entry that moves. putFirst("cara", 35) both changes Cara's value and moves her entry to the front.
The same rule applies to putLast: an existing key moves to the end, and a new key is added there.
Choosing between ordinary and end-oriented methods
Use ordinary add or put when you want normal insertion behavior. Use the end-oriented methods when position is part of the operation.
| Collection | Insert or update normally | Place at the beginning | Place at the end |
|---|---|---|---|
| `SequencedSet<E>` | `add(e)` | `addFirst(e)` | `addLast(e)` |
| `SequencedMap<K,V>` | `put(k, v)` | `putFirst(k, v)` | `putLast(k, v)` |
For a map, “beginning” and “end” refer to entry order, not to key sorting. A LinkedHashMap preserves insertion or encounter order. A TreeMap determines order with a comparator and does not support arbitrary repositioning.
Common mistakes
Do not assume that every collection supports repositioning. The interface type and implementation determine the behavior.
A sorted collection owns its order. Its comparator decides where an element belongs, so addFirst and addLast are unsupported for sorted sets. Similarly, an immutable or unmodifiable collection cannot be changed.
Also remember that moving an element changes iteration order. Code that depends on stable order may produce different results after a repositioning call.
Designing methods with sequenced interfaces
Accept the narrowest useful interface in a method parameter. This allows callers to provide different implementations while making the required behavior clear.
import java.util.SequencedSet;
public class QueueOperations {
public static <T> void promote(SequencedSet<T> items, T item) {
items.addFirst(item);
}
}This method works with a LinkedHashSet, but it cannot accept a set whose implementation does not support repositioning. If the operation can fail for a supplied implementation, document that requirement or check the implementation's behavior before calling it.
Exercise
What is the final order of set after these statements? LinkedHashSet<String> set = new LinkedHashSet<>(List.of("a", "b", "c")); set.addFirst("b"); set.addLast("a");
Show answer
The final order is [b, c, a]. The first call moves b to the front, producing [b, a, c]; the second moves a to the end.