Skip to main content
Java 21 (LTS) · Topic 4 of 4

Sequenced collections

Definition​

Sequenced collections (Java 21) add a common way to work with the first and last element and to reverse any collection that has a defined order. New methods include getFirst, getLast, addFirst, addLast and reversed.

Example code​

First, last and reversed on a list and a LinkedHashMap

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

class Demo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("b", "c"));
list.addFirst("a"); // Java 21
list.addLast("d");
System.out.println(list.getFirst() + " " + list.getLast());
System.out.println(list.reversed());

LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
System.out.println(map.firstEntry() + " " + map.lastEntry());
}
}

// Output:
// a d
// [d, c, b, a]
// one=1 three=3

Finished this page? Track your progress (saved only in your browser).