Sub topic 5
SequencedSet and LinkedHashSet
This chapter assumes you know the Set implementations (HashSet, LinkedHashSet, TreeSet), the SequencedCollection methods from earlier chapters (getFirst, addLast, reversed()), and that you run Java 21 or newer.
Why a set needs its own sequenced interface
SequencedCollection gives any collection with an encounter order operations for both ends. A Set adds a rule: no duplicates. That rule changes what "add at the front" means. If the element is already in the set, there are two reasonable answers: ignore the request, or move the element. SequencedSet exists to pin down that behavior and to make reversed() return a type that is still a set.
public interface SequencedSet<E> extends SequencedCollection<E>, Set<E> {
SequencedSet<E> reversed();
}The only method it declares is reversed() with a narrower return type. Everything else comes from SequencedCollection and Set. Because it extends both interfaces, a SequencedSet can be passed anywhere a Set or a SequencedCollection is accepted.
Where it sits in the hierarchy
Two kinds of sets are sequenced: sets that remember insertion order, and sets that sort. SortedSet now extends SequencedSet, so every TreeSet and ConcurrentSkipListSet is also a sequenced set.
Several familiar sets are not sequenced:
| Type | Sequenced? | `addFirst` / `addLast` |
|---|---|---|
| `HashSet` | No | Not available |
| `Set.of(...)` | No | Not available |
| `EnumSet` | No | Not available |
| `LinkedHashSet` | Yes | Adds, or moves an existing element |
| `TreeSet` | Yes | Throws `UnsupportedOperationException` |
| `ConcurrentSkipListSet` | Yes | Throws `UnsupportedOperationException` |
LinkedHashSet extends HashSet, but HashSet itself has no sequenced methods. Declare variables as SequencedSet or LinkedHashSet when you need the order. A variable typed HashSet or Set cannot reach the new methods, even if the object behind it is a LinkedHashSet.
Repositioning in a LinkedHashSet
Before Java 21, a LinkedHashSet kept the position of the first insertion. Calling add with an element already present did nothing, and there was no way to move an element except to remove it and add it again.
addFirst and addLast change this. After either call completes, the element is in the set and sits at the requested end, whether or not it was there before.
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class Reposition {
public static void main(String[] args) {
SequencedSet<String> set = new LinkedHashSet<>(List.of("a", "b", "c"));
boolean changed = set.add("a"); // already present: no effect
System.out.println(changed); // false
System.out.println(set); // [a, b, c]
set.addLast("a"); // moves a to the end
System.out.println(set); // [b, c, a]
set.addFirst("a"); // moves a back to the front
System.out.println(set); // [a, b, c]
set.addFirst("z"); // new element goes to the front
System.out.println(set); // [z, a, b, c]
}
}Notice the return types. add returns a boolean that says whether the set changed. addFirst and addLast return void, because after they run the element is always present at the requested end. If you need to know whether the element was new, check contains first.
Example: a recent-searches list
Repositioning is useful for "most recently used" lists. Each use moves an item to the front, no duplicates appear, and the oldest item falls off the end.
import java.util.LinkedHashSet;
import java.util.SequencedSet;
public class RecentSearches {
private final SequencedSet<String> recent = new LinkedHashSet<>();
private final int limit;
RecentSearches(int limit) {
this.limit = limit;
}
void record(String query) {
recent.addFirst(query); // new or repeated: it ends up first
if (recent.size() > limit) {
recent.removeLast(); // drop the oldest
}
}
public static void main(String[] args) {
RecentSearches searches = new RecentSearches(3);
for (String q : new String[] {"java", "spring", "java", "kotlin", "go"}) {
searches.record(q);
System.out.println(searches.recent);
}
}
}The output is:
[java]
[spring, java]
[java, spring]
[kotlin, java, spring]
[go, kotlin, java]The third line shows the repositioning: the second java moved to the front instead of being ignored. On the last line, spring was the oldest entry and was removed. Before Java 21 you would have written remove(query) followed by a re-insert, plus iterator code to find the last element.
The reversed view of a set
reversed() on a SequencedSet returns another SequencedSet. It is a live view: it holds no copy of the data, and a change through either object shows up in the other. The view also swaps the meaning of the ends, so addFirst on the view is addLast on the original.
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
public class ReversedSetView {
public static void main(String[] args) {
LinkedHashSet<String> base = new LinkedHashSet<>(List.of("a", "b", "c"));
SequencedSet<String> rev = base.reversed();
System.out.println(rev); // [c, b, a]
rev.addFirst("z"); // first in the view = last in base
System.out.println(base); // [a, b, c, z]
System.out.println(rev); // [z, c, b, a]
rev.addLast("b"); // last in the view = first in base
System.out.println(base); // [b, a, c, z]
System.out.println(rev); // [z, c, a, b]
base.removeFirst(); // removes b from both
System.out.println(rev); // [z, c, a]
}
}Repositioning rules apply through the view as well. Calling rev.addLast("b") on an element that already exists moves it, as it would on the original set.
Use reversed() when you want to iterate or stream backward:
for (String s : base.reversed()) {
System.out.println(s);
}
base.reversed().stream().limit(2).toList();Because the view is live, structural changes during iteration follow the usual fail-fast rules. Do not add or reposition elements in a set while a loop is walking over it or its view.
Sorted sets are sequenced, with limits
A TreeSet decides element positions through its comparator, so it cannot let you place an element at an end. The sequenced methods split into two groups:
- Reading and removing ends works.
getFirst,getLast,removeFirstandremoveLastbehave likefirst(),last()and thepollmethods. - Positioning throws.
addFirstandaddLastthrowUnsupportedOperationException.
reversed() on a sorted set gives you a view in the opposite order, which is useful when you want descending iteration without creating a second comparator.
import java.util.List;
import java.util.NoSuchElementException;
import java.util.SequencedSet;
import java.util.TreeSet;
public class SortedBehavior {
public static void main(String[] args) {
TreeSet<Integer> tree = new TreeSet<>(List.of(3, 1, 2));
System.out.println(tree.getFirst()); // 1
System.out.println(tree.getLast()); // 3
SequencedSet<Integer> desc = tree.reversed();
System.out.println(desc); // [3, 2, 1]
System.out.println(tree.removeFirst()); // 1
System.out.println(desc); // [3, 2]
try {
tree.addFirst(0);
} catch (UnsupportedOperationException e) {
System.out.println("addFirst is unsupported on a TreeSet");
}
try {
new LinkedHashSet<String>().getFirst();
} catch (NoSuchElementException e) {
System.out.println("getFirst on an empty set throws");
}
}
}This example needs import java.util.LinkedHashSet; as well. Add it to the imports before compiling.
Two rules help you predict which exception you get:
- An empty set throws
NoSuchElementExceptionfromgetFirst,getLast,removeFirstandremoveLast. This applies toLinkedHashSetandTreeSetalike. - A request the set cannot honor, such as
addFirston a sorted set, throwsUnsupportedOperationException.
Writing methods against the interface
Take SequencedSet<E> as a parameter when your method needs a defined order and uniqueness. The type documents both, and the compiler rejects a plain HashSet.
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
import java.util.TreeSet;
public class Newest {
static <E> E lastOr(SequencedSet<E> set, E fallback) {
return set.isEmpty() ? fallback : set.getLast();
}
public static void main(String[] args) {
System.out.println(lastOr(new LinkedHashSet<>(List.of("x", "y")), "none")); // y
System.out.println(lastOr(new TreeSet<>(List.of(5, 9, 7)), -1)); // 9
System.out.println(lastOr(new LinkedHashSet<String>(), "none")); // none
}
}The method works with insertion-ordered and sorted sets, and the meaning of "last" follows each set's own order. The empty check is needed because getLast throws on an empty set.
If the method only reads elements, SequencedCollection<E> is the wider choice. Accept SequencedSet<E> when callers also depend on uniqueness.
Equality and other compatibility notes
- Equality ignores order.
Set.equalscompares membership only. TwoLinkedHashSetobjects with the same elements in different orders are equal, andset.equals(set.reversed())is true. Do not useequalsto check order. CompareList.copyOf(a)withList.copyOf(b)instead. - Names can clash. Code that extends
LinkedHashSetor implementsSortedSetand already defines methods calledgetFirst,addFirstorreversedmay no longer compile against Java 21. Check return types andthrowsclauses of such methods. - Existing
addcalls keep their meaning. Only the new methods reposition elements. Changing a call fromaddtoaddLastis a behavior change.
Exercise
A LinkedHashSet<String> s contains [a, b, c]. You run s.addLast("a"); s.addFirst("d"); s.reversed().addFirst("b");. What is s afterward, and what does s.reversed() print?
Show answer
Step by step: addLast("a") moves a to the end, giving [b, c, a]. addFirst("d") gives [d, b, c, a]. s.reversed().addFirst("b") means "move b to the first position of the view", which is the end of the original, so s becomes [d, c, a, b]. s.reversed() prints [b, a, c, d].
Exercise
A method receives a SequencedSet<Integer> and calls addFirst(0). It works when the caller passes a LinkedHashSet but fails when the caller passes a TreeSet. What exception is thrown, why does it happen, and which two operations would still work on the TreeSet?
Show answer
A UnsupportedOperationException is thrown. A TreeSet places elements by its comparator, so the caller cannot choose a position. getFirst and removeFirst (or getLast and removeLast) still work, as does reversed(). If the method needs to choose positions, it should require a LinkedHashSet or document that sorted sets are not supported.