How to convert a 2D array of integers to a 2D array of booleans using streams in Java?

EJC :

I have a 2D array of integers (0 or 1) like so...

int [][] gridInt = {
        {0, 0, 0, 1, 0, 0},
        {0, 0, 1, 1, 0, 0},
        {1, 0, 1, 0, 0, 1},
        {0, 0, 0, 0, 1, 0},
        {0, 1, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0}
    };

and I want to convert it to a 2D array of booleans using Java streams and .map(). The resulting array being:

boolean[][] gridBool = {
        {false, false, false, true, false, false},
        {false, false, true, true, false, false},
        {true, false, true, false, false, true},
        {false, false, false, false, true, false},
        {false, true, false, false, false, false},
        {false, false, false, false, false, false}
    };

My latest attempt was:

boolean[][] gridBool = Arrays.stream(gridInt)
    .map(row -> Arrays.stream(row)
        .mapToObj(i -> i == 1)
        .toArray(Boolean[]::new)
    )
    .toArray(Boolean[][]::new);

But my code isn't compiling, the error message is:

error: incompatible types: inferred type does not conform to upper bound(s)
        .toArray(Boolean[][]::new);
                ^
inferred: Boolean[]
upper bound(s): boolean[],Object

Could you tell me what I am doing wrong and how to fix it? Thanks.

Ousmane D. :

if you require a Boolean[][] as a result then it's as simple as changing the receiver type from boolean to Boolean:

Boolean[][] gridBool = Arrays.stream(gridInt)
                .map(row -> Arrays.stream(row)
                        .mapToObj(i -> i == 1)
                        .toArray(Boolean[]::new)
                )
                .toArray(Boolean[][]::new);

However, it seems you want a boolean[][] as a result; unfortunately, since there is no BooleanStream it wouldn't be wise to perform this via a stream as readability or conciseness is not the best, rather an imperative approach would be better:

boolean[][] result = new boolean[gridInt.length][];
for (int i = 0; i < gridInt.length; i++) {
     boolean[] temp = new boolean[gridInt[i].length];
     for (int j = 0; j < gridInt[i].length; j++) 
          temp[j] = gridInt[i][j] == 1;         
     result[i] = temp;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related