Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to construct a Java stream expression to return a 2D boolean array, all values set to true?

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.

like image 721
Rob Hoff Avatar asked Nov 16 '22 04:11

Rob Hoff


1 Answers

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]
like image 187
WJS Avatar answered Dec 26 '22 01:12

WJS