Simplify First and Last Element Access with JDK 21 Sequenced Collections
JDK 21 introduces Sequenced Collections with new interfaces and unified methods, allowing developers to retrieve the first and last elements of List, Deque, and Set collections using a single, consistent API instead of disparate, cumbersome calls.
In JDK 21, the introduction of Sequenced Collections brings new interfaces and methods to simplify collection handling, addressing the previously non‑uniform and cumbersome ways of accessing the first and last elements of various Java collection types.
Sequenced Collections Interfaces
Sequenced Collections introduced three new interfaces:
SequencedCollection
SequencedMap
SequencedSet
These interfaces provide new methods that improve collection access and manipulation.
Accessing the First and Last Elements
Prior to JDK 21, retrieving the first and last elements required different calls for each collection type:
List: first element – list.get(0); last element – list.get(list.size()-1) Deque: first element – deque.getFirst(); last element – deque.getLast() SortedSet: first element – set.first(); last element – set.last() This disparity made simple operations cumbersome.
In JDK 21, ordered collections such as List, Deque, and Set share unified methods:
First element: collection.getFirst() Last element:
collection.getLast()Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
