簡體   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