Fundamentals 3 min read

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.

Programmer DD
Programmer DD
Programmer DD
Simplify First and Last Element Access with JDK 21 Sequenced Collections

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()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCollectionsJDK21SequencedCollections
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.