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.
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
There is also a reverse() method from the ArrayUtils class that belongs to the Apache Commons library. We need to add the dependency to use this class.
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!