简体   繁体   中英

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 .

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]

I've discovered a way to make a Boolean[][] array (that is, the Object type boolean, not the primitive type). The line is almost the same as the one in my question, but with a cast to Boolean[] in the first toArray()

Boolean[][] bool_array = IntStream.range(0,h).mapToObj(i->IntStream.range(0,w).
           mapToObj(j->true).toArray(Boolean[]::new)).toArray(Boolean[][]::new);

It's more expedient to use a loop. Lambda statements and streams do not fundamentally replace loops , and the simplicity you get with using loops in this context is far simpler and far easier to deal with.

Note that my answer is also based in learning about lambda expressions. When they first came out, I too thought they could do a lot of things that loops could. However , learning a new tool or approach also includes learning when not to use it, and general iteration is definitely not a circumstance when lambdas are fit for purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM