使用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.


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

10-01 07:58