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.
First 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]]
You need a toArray(generator)
method that helps us to specify a return type by an IntFunction<T[]>
function:
int[][] a = Stream.of(new int[]{1, 2, 3}, new int[]{4, 5, 6}).toArray(int[][]::new);
instead of toArray()
, which returns Object[]
regardless of an incoming type in a Stream
(invokes toArray(Object[]::new)
internally):
Object[] a = Stream.of(new int[]{1, 2, 3}, new int[]{4, 5, 6}).toArray();
If you are interested in, behind the scenes, all of this have the following look:
Node
[an ArrayNode
in our case] (an immutable container for keeping an ordered sequence of elements) from a Pipeline
of the previous stage;node.count()
);IntFunction<T[]>
generator (i -> new int[i][]
or simply int[][]::new
);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