Sub topic 2
SequencedSet and LinkedHashSet
Assume you know List, Set, Map, Deque, generics, and the difference between ordered and unordered collections. These examples require Java 21 or newer.
SequencedSet and LinkedHashSet
A SequencedSet is a Set with a defined encounter order. Encounter order is the order used when iteration visits elements. LinkedHashSet implements this interface, so it gains one API for both ends:
getFirst()andgetLast()read elements.addFirst(element)andaddLast(element)insert or reposition elements.removeFirst()andremoveLast()remove elements.reversed()returns a reverse-order view.
import java.util.LinkedHashSet;
import java.util.List;
public class SequencedDemo {
public static void main(String[] args) {
LinkedHashSet<String> set =
new LinkedHashSet<>(List.of("a", "b", "c"));
set.addFirst("c");
set.addLast("a");
System.out.println(set); // [c, b, a]
System.out.println(set.getFirst()); // c
System.out.println(set.getLast()); // a
System.out.println(set.reversed()); // [a, b, c]
set.removeFirst();
System.out.println(set); // [b, a]
}
}Calling add on an existing set element does not change its position. Calling addFirst or addLast explicitly moves it.
SequencedMap and LinkedHashMap
A SequencedMap applies the same idea to map entries. LinkedHashMap implements it. Use firstEntry, lastEntry, putFirst, putLast, pollFirstEntry, and pollLastEntry.
SequencedMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("one", 1);
scores.put("two", 2);
scores.putFirst("zero", 0);
System.out.println(scores.firstEntry()); // zero=0
System.out.println(scores.reversed()); // {two=2, one=1, zero=0}
System.out.println(scores.pollLastEntry()); // zero=0Where the Interfaces Sit in the Collections Hierarchy
| Interface | Example implementation | Defines encounter order |
|---|---|---|
| `SequencedSet` | `LinkedHashSet` | Yes |
| `SequencedMap` | `LinkedHashMap` | Yes |
| `SortedSet` | `TreeSet` | Yes, by comparator |
HashSet and HashMap do not provide a defined encounter order, so they do not implement these sequenced interfaces.
Exercise
Which method moves an existing LinkedHashSet element to the front?
Show answer
addFirst(element).