Reverse a List in Java (In-place)

In this post, we will see how to reverse a List in Java by modifying the list in-place. That means that the conversion should take place without using any auxiliary list, by overwriting the existing elements of the specified list.

 
Assume that the specified list is modifiable. For immutable lists, an UnsupportedOperationException should be thrown.


 

1. Collections.reverse()

The idea is to use Collections.reverse() method to reverse the order of the elements in the specified list.

 

Download   Run Code

Output:

[BLACK, BLUE, RED]

 

2. List.add() + List.remove()

Another approach to in-place reverse a list is to reorder the elements present in the list using a for-loop which removes an element from the end of the list and insert it into the very beginning, one at a time.

 

Download   Run Code

Output:

[BLACK, BLUE, RED]

 

3. Recursion

We can also use recursion to reverse a list in-place as demonstrated below:

 

Download   Run Code

Output:

[BLACK, BLUE, RED]

 

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of