I'm new to Java8 and I can't use streams to map one array into another 2 dimensional array.
I have one 2-dimensional array which is a pattern:
boolean[][] pattern = {
{true, true, false},
{true, false, true},
{false, true, true}
};
And second array which contains keys.
0 means: take 0-element from pattern
1 means: take 1-element from pattern and so on
int[] keys = {2, 1, 0};
From these 2 arrays I'd like to produce another 2-dimensional array. In this case the result will look like this:
boolean[][] result = {
{false, true, true},
{true, false, true},
{true, true, false}
};
This is the code in Java7:
public boolean[][] producePlan(int[] keys, boolean[][] pattern) {
boolean[][] result = new boolean[keys.length][];
for (int i = 0; i < keys.length; i++) {
result[i] = pattern[keys[i]];
}
return result;
}
In Java8 I'm only able to print every row
Arrays.stream(keys).mapToObj(x -> pattern[x]).forEach(x -> System.out.println(Arrays.toString(x)));
but can't transform it into 2-dimensional array.
Please help
You can do it like so,
boolean[][] result = Arrays.stream(keys).mapToObj(i -> pattern[i]).toArray(boolean[][]::new);
Since you have Stream<boolean[]>
after the map
stage, you only need to provide an array generator function.
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