按如下所示编译此代码时遇到问题:
int[][] result = Arrays.stream(board)
.map(r -> IntStream.range(0, board[0].length)
.map(i -> IntStream.range(0, board.length).map(j -> decideAliveOrDied(i, j, board)))
.toArray())
.toArray(int[][]::new);
面板是我们可以进行一些转换的输入矩阵。方法 decideAliveOrDied(int i,int j,int [] [] board)将每个输入矩阵的单元格转换为给定的行索引i,列索引j和矩阵板的另一个单元格。 结果矩阵是 board 矩阵上整个修改的输出。
有关我的方法 decideAliveOrDied 的更多信息:
public int decideAliveOrDied(int i, int j, int[][] board) {
int result = 0;
ArrayList<Integer> list = getNeighbors(i, j, board[0].length, board.length, board);
int numberOfLiveCell = (int) list.stream().filter(number -> number == 1).count();
if (board[i][j] == 1 && numberOfLiveCell < 2) {
result = 0;
}
if (board[i][j] == 1 && (numberOfLiveCell == 2 || numberOfLiveCell == 3)) {
result = 1;
}
if (board[i][j] == 1 && numberOfLiveCell > 3) {
result = 0;
}
if (board[i][j] == 0 && numberOfLiveCell == 3) {
result = 1;
}
return result;
}
但是我收到了如下所示的编译错误:
- Type mismatch: cannot convert from IntStream to int
- The method map(IntUnaryOperator) in the type IntStream is not applicable for the arguments ((<no
type> j) -> {})
预先感谢您的帮助。
答案 0 :(得分:2)
很难猜测您要实现的目标。据我了解,您的代码可以简化为:
int[][] finalBoard = new int[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
int result = decideAliveOrDied(i, j, board);
finalBoard[i][j] = result;
}
}
您不一定必须始终使用流。特别是当您最终拥有三个嵌套的map
时。
答案 1 :(得分:1)
真的不确定在这里stream api是很好的解决方案。但是您正在将IntStream
映射到另一个流。为此使用flatMap
:
....
.map(r -> IntStream.range(0, board[0].length)
.flatMap(i -> IntStream.range(0, board.length).map(j -> decideAliveOrDied(i, j, board)))
.toArray())
....