gpt4 book ai didi

java - 是否可以使用 Java 8 流构造 : 更简洁地表达以下逻辑

转载 作者:行者123 更新时间:2023-11-30 10:11:42 24 4
gpt4 key购买 nike

是否可以使用 Java 8 流结构更简洁地表达以下逻辑:

int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2};                                                                                                    
int[][] winningPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6},
{1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};

for (int[] winningPosition : winningPositions) {

System.out.println("RST " + gameState[winningPosition[0]] );

if (gameState[winningPosition[0]] == gameState[winningPosition[1]]
&& gameState[winningPosition[1]] == gameState[winningPosition[2]]
&& gameState[winningPosition[0]] != 2) {

// Somone has won!

gameActive = false;

String winner = "";

if (activePlayer == 1) {

winner = "Yellow";

} else {

winner = "Red";

}
}

我想将此代码更改为流式传输。

最佳答案

像这样的事情呢?

Arrays.stream(winningPositions) // Stream<int[][]>
.anyMatch(win -> // win is an int[] array
gameState[win[0]] == gameState[win[1]] &&
gameState[win[1]] == gameState[win[2]] &&
gameState[win[0]] != 2
); // anyMatch will stop as soon as match has been found.

尽管与您原来的方法相比,它可能没有任何真正的优势;

关于java - 是否可以使用 Java 8 流构造 : 更简洁地表达以下逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52294631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com