how to reverse an arraylist in java using recursion code example
Example 1: reverse arraylist java recursion
public ArrayList<Object> reverse(ArrayList<Object> arrayList) {
if(arrayList.size() > 1) {
Object value = arrayList.remove(0);
reverse(arrayList);
arrayList.add(value);
}
return arrayList;
}
Example 2: how to reverse an arraylist in java using recursion
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestSolution {
public static void main(String args[]) {
List<String> books = new ArrayList<>();
books.add("Beautiful Code");
books.add("Clean 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);
List<String> output = reverseListRecursively(books);
System.out.println("Reversed list reversed again: " + output);
}
private static List<String> reverseListRecursively(List<String> list) {
if (list.size() <= 1) {
return list;
}
List<String> reversed = new ArrayList<>();
reversed.add(list.get(list.size() - 1));
reversed.addAll(reverseListRecursively(list.subList(0, list.size() - 1)));
return reversed;
}
}
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]
Reversed list reversed again: [Beautiful Code, Clean Code, Working Effectively with Legacy Code]