What is the new Sequence
interface in Java 21? What does it add and what may be common issues to consider?
-
2Have you considered consulting the documentation? – user207421 Aug 09 '23 at 06:38
-
1@user207421 The OP is obviously not actually asking this question and is instead trying to provide a "canonical reference" for questions about `SequencedCollection` and `SequencedMap`. Now, whether you think this a worthwhile Q&A is a different issue. – Slaw Aug 09 '23 at 07:50
-
1It is encouraged to document new things and answer your own question. See https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/ – A_Arnold Aug 09 '23 at 15:20
1 Answers
The Sequence
interface is Java’s standardization of sequential Collections
that have a logical ordering, or as JEP 431: Sequenced Collections puts it, “a defined encounter order”. A SortedSet
would be able to keep its natural ordering, a List
keeps its insertion order etc.
The methods that it adds are
SequencedCollection<E> reversed();
void addFirst(E);
void addLast(E);
E getFirst();
E getLast();
E removeFirst();
E removeLast();
The getFirst()
method can replace list.get(0)
, deque.getFirst()
, sortedSet.first()
, and linkedHashSet.iterator().next()
. The same for getLast()
except LinkedHashSet
had no get last and you would have to iterate the entire Set.
There is some strangeness IMO to this regarding SortedSet
. SortedSet
is forced to implement the addFirst()
and addLast()
methods which don’t make sense in context and the Jep says “these methods can throw UnsupportedOperationException
”.
Reversed()
also standardizes how to iterate backwards. Previously, there was navSet.descendingSet()
, deque.descendingIterator()
, and for (var it = list.listIterator(list.size()); it.hasPrevious();) {}
and again LinkedHashSet
has no method. Now reversed()
allows all the standard iteration techniques of fors, streams etc. and includes LinkedHashSet
.
One final note is that if a codebase used these method names they will run into issues. See the Jep for a full description of the item.

- 303,325
- 100
- 852
- 1,154

- 3,195
- 25
- 39