How To Reverse A List In Java
Chapter:
Miscellaneous
Last Updated:
17-05-2023 15:04:05 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReverseListExample {
public static void main(String[] args) {
// Create a list
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Print the original list
System.out.println("Original list: " + numbers);
// Reverse the list
Collections.reverse(numbers);
// Print the reversed list
System.out.println("Reversed list: " + numbers);
}
}
/* ............... END ............... */
Output
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
Notes:
-
First, we create an ArrayList called numbers and add some integer values to it. In this example, we added the numbers 1, 2, 3, 4, and 5 to the list.
- Then, we print the original list using System.out.println(), which displays the list as [1, 2, 3, 4, 5].
- Next, we use the Collections.reverse() method to reverse the order of elements in the numbers list. This method modifies the original list in-place, meaning it doesn't create a new reversed list but changes the existing list itself.
- After reversing the list, we print the reversed list using System.out.println(). The reversed list is displayed as [5, 4, 3, 2, 1].
- So, the program demonstrates how to use the Collections.reverse() method to reverse the order of elements in a list in Java.
-
Tags
How to reverse a list in Java using for loop # Java program to reverse a list # Java Collections reverse