Sayan Pal Sayan Pal - 7 days ago 7
Java Question

How to generate a 2D int array using Java 8 stream?

I am trying to generate a

int[][]
using Java 8 streams.

This is what I have done so far:

objects.parallelStream()
.map(o -> o.getPropertyOnes()
.parallelStream()
.map(t-> t.getIndex()) //<-- getIndex() returns int
.mapToInt(i -> i)
.toArray()) //<-- here I have a Stream<int[]>
.toArray(); //lost here


At the end of outer
.map()
I have a
Stream<int[]>
, but not sure how to convert that to
int[][]
. Please suggest.

Answer

Fist you can simplify the map().mapToInt() to mapToInt(t-> t.getIndex()) (maybe you should use a method reference like <type>::getIndex).

As you said you have Stream<int[]> after the map stage. Then you only need to provide an array generator function like:

int[][] array = Stream.of(1, 2, 3, 4)
                      .map(i -> IntStream.range(0, i).toArray())
                      .toArray(int[][]::new);

Output:

[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]