To reverse a List in Java e.g. ArrayList or LinkedList, you should always use
the Collections.reverse() method. It's safe and tested and probably
perform better than the first version of the method you write to reverse an ArrayList in Java
In this tutorial, I'll show you how to reverse an ArrayList of String using recursion as well.
In a recursive algorithm, a function calls itself to do the job. After each pass problem
becomes smaller and smaller until it reaches to the base case.
In order to reverse a List using recursion our base case is a list of one element. If
your list contains one element then the reverse of that list is the list itself, so
just return it. Now, on each pass we need to program reaches to base case and starts
winding down, we end up all the add the last element on the list into a new list
called reversed.
import java.util.ArrayList;
import java.util.Collections;
public class TestSolution {
public static void main(String args[])
{
List books = new ArrayList<>();
books.add("Beautiful Code");
books.add("Working Effectively with Legacy Code");
System.out.println("Original order of List: " + books);
Collections.reverse(books);
System.out.println("The reversed List: " + books);
//Now, let's try to reverse a List using recursion List
output = reverseListRecursively(books);
System.out.println("Reversed list reversed again:
" + output); }
/** * A recursive algorithm to reverse a List in Java * *
@param list * @return */
private static List reverseListRecursively(Listlist) {
List reversed = new ArrayList<>();
reversed.add(list.get(list.size() - 1));
//last element
reversed.addAll(reverseListRecursively(list.subList(0, list.size() - 1)));
Output
Original order of List: [Beautiful Code, Clean Code, Working Effectively with Legacy Code]
The reversed List: [Working Effectively with Legacy Code, Clean Code, Beautiful Code]