I'm learning about stream expressions and trying to use them to construct a 2D boolean array, with all values set to true. Something like:
boolean[][] bool_array = [stream expression returning a
2D array boolean[h][w], all values set to true]
Is this possible to do and what would the expression be?
I know int[][]
arrays may be created using streams, for example
int h=5;
int w=8;
int[][] int_array = IntStream.range(0,h).mapToObj(i->IntStream.range(0,w).
map(j->1).toArray()).toArray(int[][]::new);
returns an int[5][8]
filled with ones. But trying to get this to work for boolean[][]
boolean[][] bool_array = IntStream.range(0,h).mapToObj(i->IntStream.range(0,w).
mapToObj(j->true).toArray()).toArray(boolean[][]::new);
throws an ArrayStoreException
.
If you want to do it with streams you can do it like this:
int rows = 5;
int cols = 5;
boolean[][] bool2D = IntStream.range(0, rows)
.mapToObj(r -> {
boolean[] rr;
Arrays.fill(rr = new boolean[cols], true);
return rr;
}).toArray(boolean[][]::new);
for (boolean[] b : bool2D) {
System.out.println(Arrays.toString(b));
}
Prints
[true, true, true, true, true]
[true, true, true, true, true]
[true, true, true, true, true]
[true, true, true, true, true]
[true, true, true, true, true]
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