Iterate List in Reverse Order in Java

In this post, we will discuss various ways to iterate List in reverse order in Java without actually reversing the list.


 

1. Using ListIterator

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

Java

Download   Run Code

2. Apache Common’s ReverseListIterator

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.

Java

Download

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 to the beginning of a List as it uses an Iterator behind the scenes and Iterator is not bidirectional.

Java

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().
     

Java

Download   Run Code

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

Java

Download   Run Code

 
Related Post: Java Program to Iterate over a List

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz