我有以下代码,由于必须将长流转换为数组,因此存在性能问题。 Board.getReachables() 方法返回一个流,因此能够使用流执行此 while 循环会提高性能。但是,我不确定如何继续。
int counter = 1;
while (check(board, counter)) {
for (int i = 0; i < board.length; i++) {
if (board[i] == counter) {
for (Pos reach2 :
Board.getReachables(currentTurn.getBoard().pos(i),
currentTurn.getBoard())
.toArray(Pos[]::new)) {
if (board[currentTurn.getBoard().index(reach2)] == 0) {
board[currentTurn.getBoard().index(reach2)] = counter + 1;
}
}
}
}
counter++;
}
最佳答案
将循环转换为流:
AtomicInteger counter = new AtomicInteger(1);
while (check(board, counter.get())) {
for (int i = 0; i < board.length; i++) {
if (board[i] == counter.get()) {
Board.getReachables(currentTurn.getBoard().pos(i), currentTurn.getBoard())
.filter(reach2 -> board[currentTurn.getBoard().index(reach2)] == 0)
.forEach(reach2 -> board[currentTurn.getBoard().index(reach2)] = counter.get() + 1);
}
}
counter.incrementAndGet();
}
counter
转换为 AtomicInteger
,因为它是在 lambda 中引用的,因此必须是有效的最终。
其他重构留给读者。
关于java - 将 Java while 循环转换为 Stream 以提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65871326/