Learn how to reverse an array in Java 8 using IntStream.rangeClosed() with a simple example, step-by-step explanation, and output.
- Intstream.rangeClosed(1, a.length) generates numbers from 1 to the length of the array.
- The map() method is used to access array elements in reverse order.
- a[a.length – n] gets the element from the last index to the first index.
- The toArray() method converts the stream result into an integer array.
- Arrays.toString() is used to print the reversed array in readable format.
import java.util.Arrays;
import java.util.stream.IntStream;
public class ReverseArrayTest {
public static void main(String[] args) {
int[] a = { 2, 3, 1, 1, 4, 3, 2, 5 };
int[] value = IntStream.rangeClosed(1, a.length)
.map(n -> a[a.length - n])
.toArray();
System.out.println("Reverse array value is :- " + Arrays.toString(value));
}
}
Output :
Reverse array value is :- [5, 2, 3, 4, 1, 1, 3, 2]
Java 8 Program to Reverse an Array
mport java.util.Arrays;
import java.util.Collections;
public class ReverseArrayWithoutRangeClosed {
public static void main(String[] args) {
Integer[] arr = { 2, 3, 1, 1, 4, 3, 2, 5 };
Collections.reverse(Arrays.asList(arr));
System.out.println("Reverse array value is :- " + Arrays.toString(arr));
}
}
Output :
Reverse array value is :- [5, 2, 3, 4, 1, 1, 3, 2]
FAQ
- How do you reverse an array in Java 8?
You can reverse an array in Java 8 by using IntStream.rangeClosed() and accessing array elements from the last index to the first index.
- Can we reverse an int array using Java 8 Stream API?
Yes, we can reverse an int array using Java 8 Stream API with IntStream and the map() method.
- What is the use of Arrays.toString() in this program?
Arrays.toString() is used to convert the array into a readable string format for printing.