Library contents

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

  1. Start with A, B, C
  2. Do this Read in reverse order
  3. Result C, B, A
Starting at the last item reverses the order of the three values.

Syntax

Java syntax
sales.reversed()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read 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.

From the programvar receipts = List.of("R1", "R2", "R3")
ResultR3, R2, R1
Main.java
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()));
    }
}
Output
R3, R2, R1

The reverse view visits the last receipt first and the archive retains its original order.

Advertisements

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.

From the programvar readings = List.of(18, 21, 23)
Result18 to 23
Main.java
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());
    }
}
Output
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.

GivenMira · Ivo · Bea
Worked resultBea · Ivo · Mira

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