Sub topic 4
Reversed views: iterating backwards and write-through behavior
This chapter covers reversed(), the method that returns a backwards view of a sequenced collection. It assumes you know List, Set, Deque and Map, and that you have read the earlier chapters on encounter order and SequencedCollection. You need Java 21 or newer to run the examples.
What reversed() returns
SequencedCollection declares one method for backward access:
SequencedCollection<E> reversed();Each sub-interface narrows the return type. List.reversed() returns a List, Deque.reversed() returns a Deque, SequencedSet.reversed() returns a SequencedSet, and SequencedMap.reversed() returns a SequencedMap.
The result is a view, not a copy. It holds no elements of its own and reads from and writes to the original collection, presenting the elements in the opposite encounter order. Creating one takes constant time and constant memory, however large the collection is.
Before Java 21 you had three ways to go backwards, and each had a cost:
Collections.reverse(list)reorders the list in place, which changes your data.- Copying into a new list and reversing the copy costs O(n) time and memory.
Deque.descendingIterator()andNavigableSet.descendingSet()worked only on those types, and each had its own name.
reversed() replaces all three with one method name on every type that has a defined encounter order.
Iterating and streaming in reverse
A view is an ordinary collection, so every way of consuming a collection works on it.
import java.util.ArrayList;
import java.util.List;
public class ReverseIteration {
public static void main(String[] args) {
List<String> log = new ArrayList<>(List.of("start", "load", "parse", "done"));
for (String step : log.reversed()) {
System.out.println(step); // done, parse, load, start
}
List<String> lastTwo = log.reversed().stream().limit(2).toList();
System.out.println(lastTwo); // [done, parse]
log.reversed().forEach(s -> System.out.print(s.charAt(0) + " "));
System.out.println(); // d p l s
System.out.println(log); // [start, load, parse, done]
}
}The last line shows that the original list is untouched. Reversing the view never moves elements in the underlying storage. It only changes the direction in which the view walks them.
Streams from a reversed view are ordered in the reversed direction. The limit(2) above takes the two elements that sit at the end of the original list.
Write-through behavior
Because the view shares the original's storage, a change through either one shows up in the other. The mapping between positions is mirrored: index 0 of the view is the last element of the original.
This program exercises writes in both directions:
import java.util.ArrayList;
import java.util.List;
public class WriteThrough {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
List<Integer> rev = list.reversed();
rev.set(0, 30); // view index 0 is the last element of list
System.out.println(list); // [1, 2, 30]
rev.addFirst(40); // first position of the view is the end of list
System.out.println(list); // [1, 2, 30, 40]
list.addFirst(0); // visible through the view as its last element
System.out.println(rev); // [40, 30, 2, 1, 0]
rev.removeLast(); // last of the view is the first of list
System.out.println(list); // [1, 2, 30, 40]
System.out.println(rev); // [40, 30, 2, 1]
}
}Read each line as "same operation, opposite end". addFirst on the view is addLast on the original, and removeLast on the view is removeFirst on the original. The same applies to add(e). On a list it appends to the end of the collection it is called on, so on the view it inserts at the front of the original.
Views are not snapshots
A view always reflects the current contents of the source, including changes you make after you created the view. You can create the view once and keep using it. You do not need to call reversed() again after each change to the source.
If you want a frozen reversed copy, copy it explicitly:
import java.util.ArrayList;
import java.util.List;
public class ReversedCopy {
public static void main(String[] args) {
List<Integer> source = new ArrayList<>(List.of(1, 2, 3));
List<Integer> snapshot = new ArrayList<>(source.reversed());
List<Integer> frozen = List.copyOf(source.reversed());
source.add(4);
System.out.println(snapshot); // [3, 2, 1]
System.out.println(frozen); // [3, 2, 1]
System.out.println(source.reversed()); // [4, 3, 2, 1]
}
}new ArrayList<>(view) gives you a mutable independent list. List.copyOf(view) gives you an unmodifiable one. Both cost O(n).
Modifying while iterating
A reversed view inherits the fail-fast behavior of the collection it wraps. Structural changes to the source made during an enhanced for loop over the view cause a ConcurrentModificationException on the next step:
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class ViewFailFast {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
try {
for (int x : list.reversed()) {
if (x == 3) {
list.add(99); // structural change to the source
}
}
} catch (ConcurrentModificationException e) {
System.out.println("source changed during iteration");
}
}
}The safe options are the same as for any collection. You can remove through the iterator's own remove(), use removeIf on the view, or collect the changes first and apply them after the loop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RemoveWhileReversing {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
Iterator<Integer> it = list.reversed().iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove();
}
}
System.out.println(list); // [1, 3, 5]
list.reversed().removeIf(n -> n > 3);
System.out.println(list); // [1, 3]
}
}removeIf visits elements in the encounter order of whichever collection you call it on. For a predicate without side effects the direction does not matter. If the predicate has side effects such as logging, calling it on the view makes it run in reverse order.
Which types give you a view
| Source type | `reversed()` result | Notes |
|---|---|---|
| `ArrayList`, `LinkedList` | `List` view | Fully write-through. `set`, `add`, `remove` are mirrored. |
| `ArrayDeque`, `LinkedList` as `Deque` | `Deque` view | `addFirst` on the view is `addLast` on the source. |
| `LinkedHashSet` | `SequencedSet` view | Supports reading, removal and repositioning (see the chapter on repositioning). |
| `TreeSet`, `TreeMap` | Descending view | Same result as `descendingSet()` and `descendingMap()`, with a reversed comparator. |
| `LinkedHashMap` | `SequencedMap` view | Covered in the `SequencedMap` chapter. |
| `List.of(...)`, `Collections.unmodifiableList(...)` | Unmodifiable view | The view cannot be written to either. |
For sorted collections, the view's order still comes from the comparator, now reversed. That is why you can add to the reversed view of a TreeSet, but you cannot call addFirst on it:
import java.util.List;
import java.util.TreeSet;
public class ReversedSorted {
public static void main(String[] args) {
TreeSet<Integer> tree = new TreeSet<>(List.of(3, 1, 2));
System.out.println(tree.reversed()); // [3, 2, 1]
System.out.println(tree.reversed().getFirst()); // 3
tree.reversed().add(5); // placed by the comparator
System.out.println(tree); // [1, 2, 3, 5]
System.out.println(tree.reversed()); // [5, 3, 2, 1]
}
}Immutable and unmodifiable sources
A view cannot be more permissive than its source. If the source rejects writes, so does the view, and the exception is thrown when you attempt the write, not when you call reversed():
import java.util.List;
public class ImmutableReversed {
public static void main(String[] args) {
List<Integer> fixed = List.of(1, 2, 3);
List<Integer> rev = fixed.reversed(); // allowed
System.out.println(rev); // [3, 2, 1]
try {
rev.add(0);
} catch (UnsupportedOperationException e) {
System.out.println("the view of an immutable list is read-only");
}
}
}Reading getFirst() or getLast() on a view of an empty collection throws NoSuchElementException, just as it does on the original.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Assuming `reversed()` returns a copy | Changes to one side appear in the other. | Copy with `new ArrayList<>(view)` or `List.copyOf(view)`. |
| Sorting or reordering through the view | Mirrors positions in the source, so the result is confusing. `Collections.sort(view)` sorts the source in the reversed ordering. | Sort a copy, or sort the source with a comparator. |
| Changing the source inside a loop over the view | `ConcurrentModificationException`. | Use the iterator's `remove()` or `removeIf`. |
| Expecting `view.add(x)` to insert at index 0 of the view | On a list it appends to the end of the view. | Use `addFirst(x)` for the front. |
| Writing to a view of `List.of(...)` | `UnsupportedOperationException`. | Copy the data into a mutable list first. |
| Calling `reversed()` on a plain `HashSet` or `HashMap` | Does not compile. Those types have no encounter order. | Use a `LinkedHashSet`, `LinkedHashMap` or a sorted type. |
When to use a view and when to copy
Use a view when you need to look at the data once, backwards: an iteration, a stream, or a quick getFirst() on the reversed side. It costs nothing and allocates nothing.
Copy when you need a stable result. That includes handing data to another thread, storing the reversed sequence in a field, or running code that changes the source while you still need the earlier ordering. A view stored in a field remains tied to the source's future changes, and the caller of your method may not expect that.
Views are also not thread-safe beyond what the source provides. A view of an ArrayList is as unsafe for concurrent writes as the ArrayList itself.
Exercise
Given List<Integer> list = new ArrayList<>(List.of(10, 20, 30)); and List<Integer> rev = list.reversed();, what do list and rev contain after rev.addFirst(40); list.addFirst(5);?
Show answer
list is [5, 10, 20, 30, 40] and rev is [40, 30, 20, 10, 5]. rev.addFirst(40) puts 40 at the end of the source. list.addFirst(5) puts 5 at the front of the source, which is the last position of the view.
Exercise
A method receives a List<String> and must return its last three elements in reverse order without changing the argument and without keeping any link to it. Write the body.
Show answer
return List.copyOf(items.reversed().stream().limit(3).toList()); is acceptable, but items.reversed().stream().limit(3).toList() alone is enough, because Stream.toList() already returns an unmodifiable list that is independent of the source. Returning items.reversed().subList(0, 3) would be wrong because subList is a view tied to the source (and it throws IndexOutOfBoundsException for lists shorter than three).
Exercise
Why does List.of(1, 2, 3).reversed() succeed but List.of(1, 2, 3).reversed().add(4) throw?
Show answer
reversed() only creates a read view, which is legal for any list. add is a write, and a view cannot write to a source that is unmodifiable, so it throws UnsupportedOperationException.