This post will discuss various ways to iterate a list in reverse order in Java without actually reversing the list.

1. Using ListIterator

The List interface provides a special iterator, called ListIterator, that allows bidirectional access. We can call the List.listIterator(index) method to get a ListIterator over the list elements starting from the specified position in the list. Since we need to start from the last element, the starting index would be equal to the list’s size.

Download  Run Code

2. Using Apache Common Collections

Apache Common provides ReverseListIterator that we can use to iterate list in reverse order.

The first call to next() will return the last element from the list, the next call to next() will return the previous element, and so on. hasNext() method checks if there is another element.

Download Code

3. Using for-loop

We know that List is an ordered collection, so we can access elements by their index (position) in the list using a for-loop. Please note we can’t use enhanced for-loop here to iterate from the end at the beginning of a List as it uses an Iterator behind the scenes, and Iterator is not bidirectional.

Download  Run Code

4. Java 8 – Using streams

In Java 8, we can:

  1. Get stream using List.stream().
  2. Accumulate elements of this stream into a LinkedList using Stream.collect().
  3. Get an iterator over the elements in the LinkedList in reverse sequential order using LinkedList.descendingIterator() method.
  4. Perform the print operation on elements of the list using Iterator.forEachRemaining() until all elements have been processed. We can either provide method reference System.out::println or pass lambda expression S -> System.out.println(S) to Iterator.forEachRemaining().

The following program demonstrates it:

Download  Run Code

 
We can also write a collector that collects elements in the reversed order, as shown below:

Download  Run Code

That’s all about iterating over a List in reverse order in Java.

 
Related Post:

Iterate over a List in Java