As I know to get Stream from 2 dimensional array but I want to know how I can get Stream from below 3 dimensional array?
int[][][] data = {
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
},
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
};
If you can do it with a two-dimensional array then doing it for N
dimensional array is not that difficult.
The solution can be done as follows:
IntStream result = Arrays.stream(data)
.flatMap(Arrays::stream)
.flatMapToInt(Arrays::stream);
To better help understand what is going on above, you can split the method invocations as follows:
// the call to Arrays.stream yields a Stream<int[][]>
Stream<int[][]> result1 = Arrays.stream(data);
// the call to flatMap yields a Stream<int[]>
Stream<int[]> result2 = result1.flatMap(Arrays::stream);
// the call to flatMapToInt yields a IntStream
IntStream intStream = result2.flatMapToInt(Arrays::stream);
You just need to call flatMap
another time to change the stream from int[][]
to stream of int[]
.
IntStream stream = Arrays.stream(data)
.flatMap(twoDArray -> Arrays.stream(twoDArray))
.flatMapToInt(oneDArray -> Arrays.stream(oneDArray));
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