In Java 21, sequenced collections are part of the java.util
package and are designed to maintain element insertion order, meaning the order in which elements were added is preserved. This is different from regular collections like HashSet
or HashMap
which do not guarantee order.
Java 21 introduces enhancements to sequenced collections, building on previous versions. Here’s a breakdown:
1. Sequenced Collections Overview
Sequenced collections are part of the java.util
package and are based on new interfaces:
SequencedCollection<E>
:
A collection where elements have a defined order.
Supports first/last operations efficiently.SequencedSet<E>
:
ExtendsSet<E>
+SequencedCollection<E>
. Maintains order without duplicates.SequencedMap<K,V>
:
ExtendsMap<K,V>
with sequencing: entries are ordered by insertion order.
2. Key Implementations in Java 21
LinkedHashSet<E>
→ ImplementsSequencedSet<E>
LinkedHashMap<K,V>
→ ImplementsSequencedMap<K,V>
Java 21 provides convenience methods like:
E first(); // Returns the first element
E last(); // Returns the last element
E removeFirst(); // Removes and returns first element
E removeLast(); // Removes and returns last element
void addFirst(E e); // Inserts at beginning
void addLast(E e); // Inserts at end
These methods make working with queues and deques more natural, even for standard sets and maps.
3. Example: Sequenced Collection
import java.util.LinkedHashSet;
import java.util.SequencedCollection;
public class Main {
public static void main(String[] args) {
SequencedCollection<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits.first()); // Apple
System.out.println(fruits.last()); // Cherry
fruits.addFirst("Mango");
System.out.println(fruits.first()); // Mango
fruits.removeLast();
System.out.println(fruits); // [Mango, Apple, Banana]
}
}
4. Summary of Benefits
- Maintains insertion order.
- Allows efficient first/last operations.
- Makes it easy to treat collections like deque or list, even if they are sets or maps.
- Reduces the need for custom linked list wrappers.