Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream from two dimensional array in java

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.

like image 712
SurenNihalani Avatar asked Mar 24 '14 04:03

SurenNihalani


People also ask

How do I stream a 2D array?

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.

Can we apply stream on array in Java?

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.

What does stream () Do Java?

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.

How do I turn an array into a stream?

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.


2 Answers

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.

like image 68
Rohit Jain Avatar answered Sep 20 '22 14:09

Rohit Jain


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); 
like image 30
Jacob G. Avatar answered Sep 21 '22 14:09

Jacob G.