Java List.getFirst, List.getLast and List.reversed
Java 21 exposes the first and last elements directly and offers a reverse-ordered view of a list.
A simple example
List.getFirst, List.getLast and List.reversed
- Start with A, B, C
- Do this Read in reverse order
- Result C, B, A
Syntax
sales.reversed()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead a receipt history newest first
A shop archives receipts in the order they were issued. The returns counter needs the newest receipt at the top of its screen without rearranging the archive for the accounting team.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var receipts = List.of("R1", "R2", "R3");
System.out.println(String.join(", ", receipts.reversed()));
}
}
R3, R2, R1
The reverse view visits the last receipt first and the archive retains its original order.
Find the opening and closing readings
A classroom sensor records temperatures in time order throughout the day. The teacher needs a quick summary of the first and final readings when the class compares them at dismissal.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var readings = List.of(18, 21, 23);
System.out.println(readings.getFirst() + " to " + readings.getLast());
}
}
18 to 23
The two endpoint methods return the readings at the beginning and end of this nonempty list.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. The coordinator needs to visit the entries in reverse order on the return trip. Read the order from the final entry back to the first.
What to watch for
Both endpoint accessors throw NoSuchElementException on an empty list. The reverse view reflects changes to its backing list.
Documentation for List.getFirst, List.getLast and List.reversed