Sub topic 4
Reversed Views: Iterating Backwards and Write-Through Behavior
This chapter assumes you know Java collections, generics, interfaces, and the difference between ordered and unordered collections. The examples require Java 21 or newer.
A view instead of a copy
Java 21 added reversed() to collections with a defined encounter order. The method returns a view. A view is an object that presents existing data in another way without copying the data.
For a list containing [1, 2, 3], the reversed view presents [3, 2, 1]. The original list and the view refer to the same elements. Changes through either reference are visible through the other.
import java.util.ArrayList;
import java.util.List;
public class ReversedView {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
List<Integer> reversed = list.reversed();
System.out.println(list); // [1, 2, 3]
System.out.println(reversed); // [3, 2, 1]
reversed.add(0);
list.add(4);
System.out.println(list); // [0, 1, 2, 3, 4]
System.out.println(reversed); // [4, 3, 2, 1, 0]
}
}Adding 0 to the end of reversed adds it to the front of list. Adding 4 to the end of list adds it to the end of the reversed presentation, which is the front of the original order.
Iterating and streaming in reverse
Use the view when an operation already accepts a collection or iterable. A for-each loop visits elements in reverse encounter order:
import java.util.ArrayList;
import java.util.List;
public class ReverseIteration {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ana", "Ben", "Cy"));
for (String name : names.reversed()) {
System.out.println(name);
}
names.reversed().stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}The loop prints Cy, Ben, and Ana. The stream also reads the reversed order. This avoids index arithmetic such as names.get(names.size() - 1 - i) and works with other sequenced collections.
A view is usually preferable to creating a new list when you only need to read in reverse. A copied list has separate storage and does not reflect later changes:
List<String> copy = new ArrayList<>(names.reversed());The copy preserves the order at the moment it is created. Later changes to names do not change copy.
Mutations through the reversed view
Operations through the view use reversed positioning. For a list [a, b, c], these effects apply:
| Operation on reversed view | Result in original list |
|---|---|
| `reversed.add(x)` | Adds `x` at the original front |
| `reversed.addFirst(x)` | Adds `x` at the original back |
| `reversed.removeFirst()` | Removes the original last element |
| `reversed.removeLast()` | Removes the original first element |
The exact mutation support depends on the underlying collection. A mutable ArrayList supports these operations. An unmodifiable or immutable collection may allow reading the reversed view but reject mutations with UnsupportedOperationException.
Do not structurally modify a collection while an iterator is active unless the iterator explicitly supports that operation. For example, creating a reversed view does not make arbitrary changes during a for-each loop safe. Follow the same iterator and concurrent-modification rules that apply to the original collection.
Choosing between indexes and reversed views
Use reversed() when the operation should work with the collection's encounter order and when you want a clear expression of intent. Use indexes when you need positions in the original order or need to compare an element with its exact neighbors. Remember that indexes remain based on the original collection, not on the reversed presentation.
Exercise
Given List<Integer> values = new ArrayList<>(List.of(10, 20, 30));, what are the results of values.reversed().removeFirst() followed by printing values?
Show answer
removeFirst() removes the first element of the reversed view, which is 30. The original list is then [10, 20].