How to Reverse the Order of a List or an Array in Java

Learn to Use the Collections.reverse() Method

The Collections.reverse() method is a simple way to reverse the order of elements in a list or an array in Java. In this article, we will explore how to use this method step-by-step with examples.

Reversing an ArrayList or LinkedList

To reverse the order of elements in an ArrayList or LinkedList, follow these steps:

  1. Create a list of elements using the ArrayList or LinkedList class.
sql
List<Integer> list = new ArrayList<Integer>();

or

sql
List<Integer> list = new LinkedList<Integer>();
  1. Add elements to the list.
csharp
list.add(10); list.add(20); list.add(30);
  1. Print the original order of the list.
go
System.out.println(list); // [10, 20, 30]
  1. Use the Collections.reverse() method to reverse the order of elements.
lua
Collections.reverse(list);
  1. Print the reversed order of the list.
go
System.out.println(list); // [30, 20, 10]

Reversing an Array

The Arrays class in Java does not have a built-in reverse() method. However, we can use the Collections.reverse() method to reverse an array by converting it to a list using the Arrays.asList() method.

  1. Create an array of elements.
css
Integer[] arr = {10, 20, 30};
  1. Convert the array to a list.
php
List<Integer> list = Arrays.asList(arr);
  1. Print the original order of the array.
go
System.out.println(Arrays.toString(arr)); // [10, 20, 30]
  1. Use the Collections.reverse() method to reverse the order of elements in the list.
lua
Collections.reverse(list);
  1. Print the reversed order of the array.
go
System.out.println(Arrays.toString(arr)); // [30, 20, 10]

Example Code

Here is the complete code for both examples.

csharp
import java.util.*; public class ReverseExample { public static void main(String[] args) { // Reversing an ArrayList or LinkedList List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); System.out.println(list); // [10, 20, 30] Collections.reverse(list); System.out.println(list); // [30, 20, 10] // Reversing an Array Integer[] arr = {10, 20, 30}; List<Integer> arrList = Arrays.asList(arr); System.out.println(Arrays.toString(arr)); // [10, 20, 30] Collections.reverse(arrList); System.out.println(Arrays.toString(arr)); // [30, 20, 10] } }

In conclusion, the Collections.reverse() method is a convenient way to reverse the order of elements in a list or an array in Java. By following the steps outlined in this article, you can easily implement this method in your own code.

Previous Post Next Post