We can reverse an array in Java in the following ways:
- Using the Collections.reverse() method
- Using the ArraysUtils.reverse() method
- Using the for-loop
Reverse an array in Java using the Collections.reverse() method
We can use the reverse() method from the Collections class that accepts the Collection. We just need to convert the array to a list first. You can find out how to do that in this tutorial: Convert Array to List in Java.
Example
public class Test { public static void main(String[] args) { Integer[] array = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // reverse an array Integer[] reversedArray = reverse(array); // print the elements Arrays.stream(reversedArray).forEach(item -> System.out.print(item + " ")); } public static Integer[] reverse(Integer[] array) { List arrayList = Arrays.asList(array); Collections.reverse(arrayList); return arrayList.toArray(array); } }
Output: 10 9 8 7 6 5 4 3 2 1
Reverse an array using the ArraysUtils.reverse() method
In order to use the reverse() method from the ArrayUtils class that belongs to the Apache Commons library, we need to add the dependency to our Maven project. For a detailed guide on creating a project with Maven, check out our tutorial on Create Java Project with Maven.
Example
import java.util.*; import org.apache.commons.lang3.ArrayUtils; public class Test { public static void main(String[] args) { Integer[] array = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // reverse an array ArrayUtils.reverse(array); // print the elements Arrays.stream(array).forEach(item -> System.out.print(item + " ")); } }
Output: 10 9 8 7 6 5 4 3 2 1
Reverse an array using the for-loop
We can use the for-loop to reverse an array by swapping the elements, like in the following example:
public class Test { public static void main(String[] args) { Integer[] array = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // reverse an array for (int i = 0, j = array.length - 1; j >= i; i++, j--) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } // print the elements Arrays.stream(array).forEach(item -> System.out.print(item + " ")); } }
Output: 10 9 8 7 6 5 4 3 2 1
Happy coding!