Java - Iterate Array in Reverse Order
Last Updated :
09 Dec, 2024
Improve
In Java, iterating over an array in reverse order means accessing the elements of the array from the last to the first. We have multiple ways to iterate an array in reverse order.
Example 1: The most simplest way to iterate over an array in reverse order is by using a for loop.
// Java program to iterate array in
// reverse order using for loop
public class GFG {
public static void main(String[] args) {
// taking integer array
int[] n = { 10, 20, 30, 40, 50 };
System.out.println("");
// using for loop to print array
// in reverse order
for (int i = n.length - 1; i >= 0; i--) {
System.out.print(n[i] + " ");
}
}
}
Output
50 40 30 20 10
Example 2: The other method is using an enhanced for loop, where we first reverse the array and then iterate directly on the elements.
// Java Program to iterate over an array
// in reverse order using enhanced for loop
import java.util.*;
public class Main {
public static void main(String[] args) {
// Array initialization
Integer[] arr = {10, 20, 30, 40, 50};
// Reversing the array
Collections.reverse(Arrays.asList(arr));
// Iterating over the reversed array
for (int n : arr) {
System.out.print(n + " ");
}
}
}
Output
50 40 30 20 10
Example 3: We can also use a while loop to iterate over an array in reverse order. This method is similar to the for loop but uses a condition explicitly.
// Java program to iterate over an array
// in reverse order using while loop
public class Main {
public static void main(String[] args) {
// Array initialization
int[] arr = {10, 20, 30, 40, 50};
int i = arr.length - 1;
// Iterating over the array in reverse order
while (i >= 0) {
// Accessing each element of the array
System.out.print(arr[i] + " ");
i--;
}
}
}
Output
50 40 30 20 10
Example 4: We can also use the Streams API in Java 8 and later, which provides a concise way to iterate over an array in reverse order.
// Java Program to iterate over an array
// in reverse order using Streams API
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Array initialization
int[] arr = {10, 20, 30, 40, 50};
// Iterating over the array in reverse
// order using Streams
IntStream.range(0, arr.length)
.map(i -> arr[arr.length - i - 1])
.forEach(i -> System.out.print(i + " "));
}
}
Output
50 40 30 20 10