Sub topic 5
SequencedSet and LinkedHashSet
This chapter assumes that you know Set, List, Deque, generics, interfaces, and the difference between insertion order and sorted order. The examples require Java 21 or newer.
What is a sequenced set?
A sequenced set is a set with a defined encounter order. Encounter order is the order in which iteration visits the elements.
SequencedSet<E> is a Java 21 interface that combines set behavior with operations for both ends of that order:
- A set still rejects duplicate elements.
- The set has a first and last element.
- You can read, remove, or add elements at either end.
- You can obtain a reversed live view.
Before Java 21, LinkedHashSet preserved insertion order, but it did not provide named operations such as getFirst() or addLast(). Code often converted the set to a list or used an iterator to find an end element.
LinkedHashSet implements SequencedSet
LinkedHashSet is the main insertion-ordered implementation of SequencedSet. Its encounter order normally follows insertion order.
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class SetEnds {
public static void main(String[] args) {
SequencedSet<String> names =
new LinkedHashSet<>(List.of("b", "c", "d"));
names.addFirst("a");
names.addLast("e");
System.out.println(names); // [a, b, c, d, e]
System.out.println(names.getFirst()); // a
System.out.println(names.getLast()); // e
names.removeFirst();
names.removeLast();
System.out.println(names); // [b, c, d]
}
}Using SequencedSet as the variable type makes the required behavior clear without tying the method to LinkedHashSet. A method can accept any compatible sequenced set:
import java.util.SequencedSet;
public class SetUtilities {
public static <E> void printEnds(SequencedSet<E> set) {
if (set.isEmpty()) {
System.out.println("The set is empty");
return;
}
System.out.println("first: " + set.getFirst());
System.out.println("last: " + set.getLast());
}
}Repositioning existing elements
For a LinkedHashSet, addFirst and addLast do more than insert missing elements. If the element is already present, these methods move it to the requested end.
Plain add does not reposition an existing element.
import java.util.LinkedHashSet;
import java.util.List;
public class Repositioning {
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.add("c");
System.out.println(set); // [c, b, a]
}
}This behavior is useful for an insertion-ordered cache or a list of recently used items. Calling addLast(item) can move an existing item to the most-recent position while preserving set uniqueness.
| Operation | Missing element | Existing element |
|---|---|---|
| `add` | Inserts according to the implementation's normal rule | Leaves its position unchanged |
| `addFirst` | Inserts at the front | Moves to the front |
| `addLast` | Inserts at the end | Moves to the end |
Reversed views
reversed() returns a view whose encounter order is the opposite of the original set. It does not create an independent copy.
Changes made through either set are visible through the other view:
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class ReversedSet {
public static void main(String[] args) {
SequencedSet<Integer> set =
new LinkedHashSet<>(List.of(1, 2, 3));
SequencedSet<Integer> reverse = set.reversed();
reverse.addFirst(0);
set.addLast(4);
System.out.println(set); // [0, 1, 2, 3, 4]
System.out.println(reverse); // [4, 3, 2, 1, 0]
}
}The operation reverse.addFirst(0) adds 0 to the front of the reversed order. That position is the end of the original order, so the result may require careful reasoning. When code uses a reversed view, name the view clearly and document which order each operation refers to.
Sorted sets and unsupported operations
TreeSet also has a defined encounter order, based on its comparator or natural ordering. It supports getFirst() and getLast(), but its order is controlled by sorting. Moving an element arbitrarily to the front or end conflicts with that rule, so addFirst() and addLast() throw UnsupportedOperationException.
Calling getFirst() or getLast() on an empty sequenced set throws NoSuchElementException. Check isEmpty() first when an empty set is possible.
Exercise
A LinkedHashSet contains [red, green, blue]. What are the contents after addFirst("blue") followed by addLast("red")?
Show answer
[blue, green, red]. Each existing element moves to the requested end, and no duplicate is added.