繁体   English   中英

如何使用Java中的流将整数的2D数组转换为布尔的2D数组?

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

我有一个2D整数数组(0或1),就像这样...

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}
    };

我想使用Java流和.map()将其转换为2D布尔数组。 结果数组为:

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}
    };

我最近的尝试是:

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

但是我的代码没有编译,错误消息是:

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

您能告诉我我在做什么错以及如何解决吗? 谢谢。

您可以将结果Array更改为Boolean

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

mapToObj需要一个Object ,而不是基本类型boolean ,因此我们不能使用toArray(boolean[][]::new)

如果需要使用Boolean[][]作为结果,那么就像将接收器类型从boolean更改为Boolean一样简单:

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

但是,似乎您需要使用boolean[][]作为结果。 不幸的是,由于没有BooleanStream因此通过流执行此操作并不明智,因为可读性或简洁性不是最好的,而命令式方法会更好:

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;
}

您可以将逻辑简化为:

boolean[][] gridBool = new boolean[gridInt.length][gridInt[0].length]; // NxN grid
for (int i = 0; i < gridInt.length; i++) {
    for (int j = 0; j < gridInt[0].length; j++) {
        gridBool[i][j] = gridInt[i][j] != 0;
    }
}

注意 :这样可以避免每次迭代都临时创建数组,因此可以节省更多空间,并且可以预先用精确的边界初始化数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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