Skip to main content

Java 21 Sequenced Collections with Practical Examples

For decades, accessing the first or last element of a collection in Java required boilerplate code that varied wildly depending on the underlying data structure. If you used a List, you called get(0) and get(list.size() - 1). If you used a Deque, you used getFirst() and getLast(). If you used a SortedSet, you relied on first() and last(). Traversing a collection in reverse order meant wrapping things in NavigableSets or writing custom loops. Java 21 resolves this architectural inconsistency with JEP 431: Sequenced Collections.

Pick a language, then press Listen.

This feature introduces three new interfaces—SequencedCollection, SequencedSet, and SequencedMap—to the existing collections framework. They standardize access to elements at both ends of a collection and enable uniform reverse-order operations. When paired with modern runtimes, such as those discussed in the Spring Boot 3 and Java 21 Virtual Threads Performance Guide, these interfaces simplify high-throughput data processing.

The Structural Hierarchy of Sequenced Collections

Java 21 Sequenced Collections Architecture Java 21 Sequenced Collections Architecture 1 Identify Structural Inconsistency Recognize fragmented APIs across List, Deque, and SortedSet. 2 Adopt JEP 431 Interfaces Implement SequencedCollection, SequencedSet, and SequencedMap. 3 Retrofit Existing Classes Update ArrayList, LinkedHashSet, and LinkedHashMap subtypes. 4 Standardize Endpoint Operations Use uniform methods to get, add, or remove first and last items. 5 Execute Reverse Operations Call reversed() view for efficient bidirectional processing.
Figure: Java 21 Sequenced Collections Architecture

Before Java 21, the Java Collections Framework lacked a common supertype that represented collections with a defined encounter order. List and Deque both maintained order, but they inherited from separate branches of the Collection interface. Sequenced Collections insert new abstractions into the hierarchy without breaking backwards compatibility.

The core interfaces are:

  • SequencedCollection<E>: A subtype of Collection<E> that has a defined encounter order. It provides methods for adding, removing, and examining elements at the first and last positions, plus a method to obtain a reversed view.
  • SequencedSet<E>: A subtype of SequencedCollection<E> and Set<E> that contains no duplicate elements.
  • SequencedMap<K, V>: A subtype of Map<K, V> where entries have a defined encounter order. It provides methods to manipulate entries at both ends and returns sequenced views of keys, values, and entries.

Existing classes like ArrayList, LinkedList, LinkedHashSet, TreeSet, LinkedHashMap, and TreeMap have been retrofitted to implement these new interfaces.

Core API Methods and Practical Examples

The new methods fall into three primary categories: retrieval, addition/removal at endpoints, and reversal. The following sections demonstrate these capabilities with production-grade code examples.

Retrieving and Modifying First and Last Elements

Consider a scenario where you manage a caching layer using a LinkedHashMap or an active session tracker using a LinkedHashSet. Previously, getting the most recently added element required casting or complex iterator logic. Now, you can invoke direct methods on the interface.

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

public class SessionTracker {
    public static void main(String[] args) {
        SequencedSet<String> activeSessions = new LinkedHashSet<>();
        
        // Adding elements maintains encounter order
        activeSessions.add("user_alpha");
        activeSessions.add("user_beta");
        activeSessions.add("user_gamma");

        // Accessing first and last elements
        System.out.println("Oldest active session: " + activeSessions.getFirst()); // user_alpha
        System.out.println("Newest active session: " + activeSessions.getLast());   // user_gamma

        // Removing elements from endpoints
        String expiredSession = activeSessions.removeFirst();
        System.out.println("Evicted: " + expiredSession);
        System.out.println("New oldest: " + activeSessions.getFirst()); // user_beta
    }
}

Working with Reversed Views

One of the most powerful additions is the reversed() method. This method returns a reverse-ordered view of the original collection. It does not copy the data; instead, it provides a window into the original collection where all operations are mirrored. Modifications made to the reversed view affect the underlying collection directly.

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

public class AuditTrail {
    public static void main(String[] args) {
        SequencedCollection<String> logEntries = new ArrayList<>();
        logEntries.add("INFO: Application started");
        logEntries.add("DEBUG: Loading configuration");
        logEntries.add("ERROR: Database connection failed");

        // Obtain a reversed view to process logs newest-first
        SequencedCollection<String> recentFirst = logEntries.reversed();

        System.out.println("--- Processing Logs In Reverse ---");
        for (String entry : recentFirst) {
            System.out.println(entry);
        }

        // Modifying the view affects the underlying collection
        recentFirst.addFirst("CRITICAL: System shutdown initiated");
        
        System.out.println("Original collection first element: " + logEntries.getLast());
        // Output: CRITICAL: System shutdown initiated
    }
}

Sequenced Maps in Action

Maps have historically been tricky to query from the ends. SequencedMap bridges this gap by exposing methods like firstEntry(), lastEntry(), pollFirstEntry(), and pollLastEntry(), returning Map.Entry objects.

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

public class ConfigurationRegistry {
    public static void main(String[] args) {
        SequencedMap<String, String> settings = new LinkedHashMap<>();
        
        settings.put("timeout", "30s");
        settings.put("retries", "3");
        settings.put("mode", "strict");

        // Accessing first and last entries
        System.out.println("First Entry: " + settings.firstEntry()); // timeout=30s
        System.out.println("Last Entry: " + settings.lastEntry());   // mode=strict

        // Polling (retrieving and removing) the last entry
        var removed = settings.pollLastEntry();
        System.out.println("Removed: " + removed);
        
        // Sequenced views for keys and entries
        System.out.println("Reversed keys: " + settings.sequencedKeySet().reversed());
    }
}

Comparison of Interface Capabilities

The following table outlines how the new sequenced interfaces map across standard Java collections and their primary operational characteristics.

Collection Type Implements First/Last Access Reversed View Supported Performance Complexity
ArrayList SequencedCollection O(1) first, O(1) last Yes O(1) index access, O(N) middle shifts
LinkedList SequencedCollection O(1) first, O(1) last Yes O(1) endpoint insertion/removal
LinkedHashSet SequencedSet O(1) first, O(1) last Yes O(1) hash table operations
TreeSet SequencedSet O(log N) first/last Yes O(log N) balanced tree operations
LinkedHashMap SequencedMap O(1) first, O(1) last Yes O(1) map operations with linked nodes
TreeMap SequencedMap O(log N) first/last Yes O(log N) sorted tree operations

Real-World Edge Cases

When adopting Sequenced Collections in production environments, developers must account for specific edge cases regarding mutability, null handling, and concurrency.

1. Structural Modification Exceptions on Reversed Views

Iterating over a reversed view while structurally modifying the underlying collection through a separate reference can trigger unexpected behavior or ConcurrentModificationException in fail-fast collections. Because the reversed view is a live projection, structural modifications must respect iterator contracts. If you need to mutate a collection while iterating through it, use explicit iterator removal or perform operations on the view itself.

2. Null Values and Optional Returns in Maps

When calling firstEntry() or lastEntry() on an empty SequencedMap, the methods return null rather than throwing an exception or returning an Optional. This design choice maintains consistency with older legacy methods like TreeMap.firstEntry(). Developers accustomed to modern Optional-based APIs must remember to guard against null references when inspecting potentially empty maps.

3. Performance Footguns with LinkedList vs. ArrayList

While both ArrayList and LinkedList implement SequencedCollection, their performance profiles at endpoints differ drastically. Calling addFirst() on an ArrayList requires shifting every existing element in memory, resulting in O(N) time complexity. For high-frequency endpoint insertions, developers must choose LinkedList or ArrayDeque to maintain O(1) performance.

Troubleshooting Common Issues

Problem: Calling addFirst() on an unmodifiable collection view (such as one created via List.of()) throws an UnsupportedOperationException.

Solution: Factory methods like List.of(), Set.of(), and Map.of() produce immutable collections. Even though these collections have a defined encounter order, they do not support mutation methods added by Sequenced Collections. If you need a modifiable sequenced collection, instantiate a concrete implementation explicitly, such as new ArrayList<>() or new LinkedHashMap<>().

Problem: Compilation errors arise when migrating custom collection wrappers that implement Collection directly but do not extend the new interfaces.

Solution: If you wrote custom collection classes prior to Java 21, they implement Collection or List without implementing SequencedCollection. Ensure your custom implementations implement the appropriate sequenced sub-interfaces and override the required abstract methods like getFirst(), getLast(), and reversed().

Summary

  • Java 21 introduces JEP 431, standardizing element access at both ends of ordered collections through SequencedCollection, SequencedSet, and SequencedMap.
  • Existing classes such as ArrayList, LinkedHashSet, and LinkedHashMap now support uniform endpoint operations like getFirst(), getLast(), removeFirst(), and removeLast().
  • The reversed() method provides a live, bidirectional view of a collection without copying underlying data structures.
  • Care must be taken with performance characteristics when calling mutation methods on contiguous memory structures like ArrayList versus pointer-based structures like LinkedList.
  • Methods querying empty maps return null rather than Optional, requiring explicit null checks in production code.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...