Java 21 introduces several new features and enhancements in Collections, especially with the ongoing development of the Stream API, immutable collections, and sequenced collections.
Here are the important new features in Collections in Java 21:
✅ 1. Sequenced Collections (JEP 431) — 🔥 New!
📌 What?
Introduces a new SequencedCollection
interface that adds first/last element access and reversible traversal to collections.
📦 New Interfaces:
✅ Applies to:
-
ArrayDeque
-
LinkedList
-
TreeSet
-
ArrayList
(viaSequencedCollection
interface) -
HashSet
-
Map
types → viaSequencedMap
🔍 Example:
✅ 2. Unmodifiable Collections Enhancements
Previously, Map.of(...)
, List.of(...)
, etc. returned immutable collections. With SequencedCollection, now you can traverse them in order and reverse:
✅ 3. Immutable SequencedMap
and SequencedSet
You can now work with insertion-ordered maps and sets:
✅ 4. Pattern Matching + Collections (Java 21 + Preview)
Pattern matching can now destructure collections (as a preview feature):
✅ 5. Stream Improvements
➕ Stream.mapMulti()
(Added in Java 16, still crucial)
Gives better performance and flexibility than flatMap
.
🔮 Optional Preview Features in Java 21 (might impact future collection usage)
-
Record Patterns
-
String Templates
-
Scoped Values (for threads)
✅ Summary Table
Feature | Description | Example Class |
---|---|---|
SequencedCollection | New interface for order-aware collections | ArrayList, LinkedList |
reversed() | Reverses any sequenced collection/map | List, Set, Map |
addFirst() , getLast() | First/last item access | SequencedCollection |
SequencedMap | Ordered maps with head/tail access | LinkedHashMap, TreeMap |
Pattern Matching (preview) | Destructure lists/maps | instanceof usage |
No comments:
Post a Comment