This is the third solution to reverse all the numbers in the given array. This solution uses IntStream, range and map methods.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ReverseArrayNumbersUSingStream {
public static void main(String[] args) {
int [] arrNums= {10,2,41,13,8,6,7,15,1};
System.out.println("Array values before reverse- below");
Arrays.stream(arrNums).forEach(x->System.out.print(x+" "));
System.out.println("\nArray values after reverse- below");
//Map each index to the element of the array in the reverse order
IntStream.range(0, arrNums.length)
.map(i -> arrNums[arrNums.length - i - 1])
.forEach(e->System.out.print(e+" "));
}
}
Output:
Array values before reverse- below
10 2 41 13 8 6 7 15 1
Array values after reverse- below
1 15 7 6 8 13 41 2 10

Leave a comment