In the previous post, we have discussed how to in-place reverse a list in Java. This post will discuss how to reverse an ArrayList in Java by creating a copy of it in reverse order without altering the ordering of elements in the original list. The specified list may or may not be mutable, but the returned list should be mutable.

1. Using Guava Library

Guava’s Lists.reverse() method creates a view of the specified list in reversed order. Since the original list backs the returned list, changes in the returned list are reflected in this list and vice-versa.

We can avoid this by creating a new ArrayList instance from the returned list, as shown below:

Download Code

Output:

[5, 4, 3, 2, 1]

2. Using Collections.reverse() method

We know that the Collections.reverse() method modifies the list in-place. The idea is to create a copy of the original list and then call the reverse() method on the copy rather than the original list.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

 
Here’s is another way in Java 8 and above that uses Collections.reverse() along with Stream, and Collectors.collectingAndThen() method, which collects elements in the reversed order:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

3. Using Java 8

We can also use Java 8 Stream to reverse a list. The idea is to get a stream of all valid indices of the list in reverse order and map each index to its value in the list, and finally collect the elements in an ArrayList.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

 
Here’s even shorten version of the above utility method:

4. Extending AbstractList Class

AbstractList class provides a skeletal implementation of the List interface. The idea is to extend this class and provide implementations for the get(), set(), remove(), etc. methods, which should behave like a reversed list.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

5. Naive solution

Finally, this post is incomplete without discussing naive ways to reverse the list. The basic idea is to create an empty ArrayList and add elements of the original list to it by iterating the list in reverse order.

⮚ Java 8 – descendingIterator()

The idea is to accumulate elements of the given list into a LinkedList using Stream. Then we get an iterator over the elements in the LinkedList in reverse sequential order using LinkedList.descendingIterator() method and process each element using forEachRemaining() method:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

List.listIterator()

Here, the idea is to use a ListIterator to iterate list in reverse order.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

⮚ For loop

We can also iterate the list in reverse order using a simple for-loop, as shown below:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

That’s all about reversing an ArrayList in Java.