Sayan Pal Sayan Pal - 3 months ago 33
Java Question

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

I am trying to generate a

using Java 8 streams.

This is what I have done so far:

.map(o -> o.getPropertyOnes()
.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
I have a
, but not sure how to convert that to
. Please suggest.


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())


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