Collections: List.getFirst() and getLast() replace get(0) and get(size()-1)

Java 21's SequencedCollection adds getFirst/getLast/addFirst/addLast to every List, so common endpoint access no longer needs get(0) or get(size()-1); an immutable List.of still rejects the mutating ones.

Code
List<String> names = new ArrayList<>(List.of("Ann", "Bo", "Cy"));
System.out.println("First: " + names.getFirst());
System.out.println("Last: " + names.getLast());
names.addFirst("Aaa");
names.addLast("Zz");
System.out.println("After addFirst/addLast: " + names);
List<String> immutable = List.of("X", "Y");
try {
    immutable.addFirst("W");
} catch (UnsupportedOperationException e) {
    System.out.println("Immutable list rejects addFirst: " + e.getClass().getSimpleName());
}
Output
First: Ann
Last: Cy
After addFirst/addLast: [Aaa, Ann, Bo, Cy, Zz]
Immutable list rejects addFirst: UnsupportedOperationException
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms