Collections

Iterate List in Reverse order in Java Example

Iterate List in reverse order or backward direction Java example shows how to iterate list (LinkedList, ArrayList) in reverse order or backward direction in Java using various approaches.

How to iterate list in reverse order or backward direction?

Let’s first create a List and populate it with some objects. We are going to use example Student class objects to populate the List.

There are several ways in which you can iterate list in reverse direction as given below.

1) Iterate list in reverse order using for loop

You can use for loop with index starting at (size of the list – 1) and index decremented by one with each iteration till it becomes zero as given below.

List index starts from 0 and goes up to the size of the list – 1. We are decreasing index by 1 with each iteration till index becomes 0. The loop prints elements of a List in reverse direction i.e. last element first and so on.

2) Iterate list in reverse order using ListIterator

You can use ListIterator to iterate a list in reverse direction using below given method.

This method returns a listIterator which starts at the specified position in the List.

In our case, since we want to traverse a list in backward direction, we are going to set the listIndex after the last element and iterate the list using hasPrevious and previous methods as given below.

3) Iterate list in reverse order using reverse method of Collections class

You can reverse the list first using reverse method of Collections class and then print the list using for loop or enhanced for loop like given below.

4) Iterate LinkedList in reverse order using descendingIterator method

If you are using LinkedList instead of ArrayList, you can get the reverse Iterator using descendingIterator method of LinkedList class. The iterator returned by this method returns list elements in reverse order.

5) Iterate list in reverse order using Apache Commons

If you are using Apache Commons Collections library, you can use ReverseListIterator to iterate List in reverse direction as given below.

6) Iterate list in reverse order using Custom Iterator

You can create your own Iterator implementation which allows iterating a list in reverse direction. We need to implement Iterable and Iterator interfaces in order to create a custom Iterator as given below.

A custom Iterator must implement three methods hasNext, next and remove. Basically, we have wrapped ListIterator into a custom Iterator. So we internally call hasPrevious method of listIterator when hasNext method of custom iterator is called. Similarly, we call previous method of ListIterator when next method of custom iterator is called. Here is how to use it in your program.

See Also: How to iterate over List example

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.