Java Sequenced Collections

Java Programming Tutorials


Java sequenced collections provide a common API for collections and maps with a defined encounter order. Introduced in Java 21, the feature adds the SequencedCollection, SequencedSet, and SequencedMap interfaces so you can work with the first element, last element, and reverse order consistently.

Before these interfaces, ordered collection types exposed different ways to access their ends. A List used indexes, a Deque had first and last methods, and LinkedHashMap required other patterns. Sequenced interfaces give these types a shared vocabulary.

SequencedCollection Methods

SequencedCollection extends Collection and represents elements arranged from first to last.

  • addFirst() and addLast() add elements at either end when the implementation supports explicit positioning.
  • getFirst() and getLast() read the first or last element.
  • removeFirst() and removeLast() remove and return an end element.
  • reversed() returns a reverse-ordered view.

The reversed collection is a view, not an independent copy. Supported changes made through the view can affect the original collection.

Use Sequenced Methods with a List

List is a SequencedCollection in Java 21 and later, so familiar list implementations can use the common end operations.

Example:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>(
            List.of("Test", "Deploy")
        );

        // List is a SequencedCollection in Java 21+.
        tasks.addFirst("Plan");
        tasks.addLast("Monitor");

        System.out.println("First: " + tasks.getFirst());
        System.out.println("Last: " + tasks.getLast());
        System.out.println("Reverse: " + tasks.reversed());
    }
}

Output:

First: Plan
Last: Monitor
Reverse: [Monitor, Deploy, Test, Plan]

Understand reversed()

The reversed() method presents the same collection with its encounter order inverted. The original first element appears last in the view, and the original last element appears first.

Example:

import java.util.ArrayList;
import java.util.List;

List<Integer> numbers =
    new ArrayList<>(List.of(10, 20, 30));

List<Integer> reverse = numbers.reversed();

System.out.println(reverse);
reverse.removeFirst();

System.out.println(numbers);

Output:

[30, 20, 10]
[10, 20]

Because the reversed list is a view, removing its first element removes the original list's last element.

SequencedSet

SequencedSet combines Set uniqueness with a defined encounter order. LinkedHashSet and sorted set types participate in this API.

A LinkedHashSet can expose its first and last elements without converting to a list. Its reversed() method returns a SequencedSet view with the encounter order inverted.

import java.util.LinkedHashSet;
import java.util.SequencedSet;

SequencedSet<String> cities =
    new LinkedHashSet<>();

cities.add("Indore");
cities.add("London");
cities.add("Seattle");

System.out.println(cities.getFirst());
System.out.println(cities.getLast());

SequencedMap

SequencedMap applies encounter order to key-value mappings. LinkedHashMap and sorted map implementations can provide ordered operations through this interface.

  • firstEntry() and lastEntry() read end mappings.
  • pollFirstEntry() and pollLastEntry() remove end mappings.
  • putFirst() and putLast() position mappings at either end when supported.
  • sequencedKeySet(), sequencedValues(), and sequencedEntrySet() provide ordered views.
  • reversed() returns a reverse-ordered map view.

Example:

import java.util.LinkedHashMap;
import java.util.SequencedMap;

SequencedMap<String, Integer> scores =
    new LinkedHashMap<>();

scores.put("Asha", 91);
scores.put("Noah", 86);
scores.put("Mia", 94);

System.out.println(scores.firstEntry());
System.out.println(scores.lastEntry());
System.out.println(scores.reversed());

Supported Operations Depend on the Collection

The sequenced interfaces define a common API, but not every implementation can support every positional change. A sorted collection determines position from its comparator or natural ordering, so explicitly adding an element first or last can conflict with that rule.

For such implementations, optional positioning operations can throw UnsupportedOperationException. Read operations and reversed views still provide a consistent way to work with encounter order.

Why Sequenced Collections Are Useful

Need Sequenced API
Read the beginning of an ordered collection getFirst() or firstEntry()
Read the end getLast() or lastEntry()
Process the same data backward reversed()
Remove an end item removeFirst(), removeLast(), or poll methods
Expose ordered map views sequencedKeySet(), sequencedValues(), sequencedEntrySet()

Common Mistakes

  • Treating reversed() as a copy: it is generally a view connected to the underlying collection.
  • Assuming every mutation is supported: ordered or unmodifiable implementations can reject optional operations.
  • Ignoring empty collections: methods such as getFirst() and getLast() require an element to be present.
  • Forgetting order semantics: Set equality still follows Set rules, and Map equality still follows Map rules; encounter order does not redefine equality.

Best Practices

  • Program to SequencedCollection or SequencedMap when your algorithm needs ordered end operations instead of a specific implementation.
  • Use reversed() when you need a view rather than building a copied collection solely to iterate backward.
  • Check whether a chosen implementation supports positional mutation before relying on addFirst(), addLast(), putFirst(), or putLast().

Conclusion

Java sequenced collections standardize how ordered collections, sets, and maps expose their first and last elements and reverse encounter order. The API makes ordered algorithms easier to express across multiple collection types while preserving each implementation's own rules for mutation, sorting, and uniqueness.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram