To reverse a list in Java, you can use the built-in Collections.reverse()
method or manually reverse the list by iterating over it and swapping elements from both ends.
In this example,
originalList
containing elements in the original order.Collections.reverse()
method to reverse the list in-place.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.reverse(originalList);
System.out.println("Reversed list: " + originalList);
}
}
Reversed list: [5, 4, 3, 2, 1]
In this example,
originalList
containing elements in the original order.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int start = 0;
int end = originalList.size() - 1;
while (start < end) {
int temp = originalList.get(start);
originalList.set(start, originalList.get(end));
originalList.set(end, temp);
start++;
end--;
}
System.out.println("Reversed list: " + originalList);
}
}
Reversed list: [5, 4, 3, 2, 1]
In this tutorial, we learned How to Reverse a List in Java language with well detailed examples.