I am trying to get an IntStream
out of an n dimensional int
arrays. Is there a nice API way to do it? I know the concatenate method for two streams.
First it invokes the Arrays. stream(T[]) method, where T is inferred as int[] , to get a Stream<int[]> , and then Stream#flatMapToInt() method maps each int[] element to an IntStream using Arrays. stream(int[]) method. h.j.k.
The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
A good way to turn an array into a stream is to use the Arrays class' stream() method. This works the same for both primitive types and objects.
Assuming you want to process array of array sequentially in row-major approach, this should work:
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; IntStream stream = Arrays.stream(arr).flatMapToInt(x -> Arrays.stream(x));
First it invokes the Arrays.stream(T[])
method, where T
is inferred as int[]
, to get a Stream<int[]>
, and then Stream#flatMapToInt()
method maps each int[]
element to an IntStream
using Arrays.stream(int[])
method.
To further expand on Rohit's answer, a method reference can be used to slightly shorten the amount of code required:
int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; IntStream stream = Arrays.stream(arr).flatMapToInt(Arrays::stream);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With