Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Stream from 3 dimensional array in Java 8?

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}
                    }
                  };
like image 647
hitesh.incept Avatar asked Jan 03 '23 07:01

hitesh.incept


2 Answers

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);
like image 149
Ousmane D. Avatar answered Feb 13 '23 12:02

Ousmane D.


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));
like image 44
Yassin Hajaj Avatar answered Feb 13 '23 10:02

Yassin Hajaj