简体   繁体   English

有人可以简要向我解释IntStream发生了什么吗?

[英]Can somebody please briefly explain to me what's happening with the IntStream?

I looked up multiple examples online but I just can't seem to grasp what's happening here. 我在网上查找了多个示例,但似乎无法理解这里发生的事情。 When the program prints out the current player and the scores, it's not apparent to me where these are stored. 当程序打印出当前的球员和比分时,对我来说这些存储位置并不明显。 I'm a begginer and I was told to analyze this piece of code to help "better understand" our current class project. 我是一个初学者,被告知我分析这段代码以帮助“更好地理解”我们当前的课堂项目。

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;

public interface PigDice {
    public static void main(String... arguments) {
        final int maxScore = 100;
        final int playerCount = 2;
        final String[] yesses = { "y", "Y", "" };

        final Scanner scanner = new Scanner(System.in);
        final Random random = new Random();

        final int[] safeScore = new int[2];
        final int[] score = new int[2];

        IntStream.iterate(0, player -> (player + 1) % playerCount).map(player -> {
            boolean isRolling = true;
            while (isRolling) {
                System.out.printf("Player %d: (%d, %d) Rolling? (y/n) ", player, safeScore[player], score[player]);
            isRolling = safeScore[player] + score[player] < maxScore
                    && Arrays.asList(yesses).contains(scanner.nextLine());
                if (isRolling) {
                    final int rolled = random.nextInt(6) + 1;
                    System.out.printf("Rolled %d\n", rolled);
                    if (rolled == 1) {
                        System.out.printf("Bust! You lose %d but keep %d\n\n", score[player], safeScore[player]);
                        return -1;
                    } else {
                        score[player] += rolled;
                    }
                } else {
                    safeScore[player] += score[player];
                    if (safeScore[player] >= maxScore) {
                        return player;
                    }
                    System.out.printf("Sticking with %d\n\n", safeScore[player]);
                }
            }
            score[player] = 0;
            return -1;
        }).filter(player -> player > -1).findFirst().ifPresent(
                player -> System.out.printf("\n\nPlayer %d wins with a score of %d", player, safeScore[player]));
    }
}

To understand what this code does, I'd first apply a couple key refactorings: 为了理解这段代码的作用,我首先要应用几个关键的重构:

  1. Promote all of main() 's local variables to static variables of the PigDice class. main()的所有局部变量提升为PigDice类的静态变量。

  2. Extract the big multi-line lambda that's passed to map() into a static method of the PigDice class. 将传递给map()的大型多行lambda提取到PigDice类的静态方法中。 Call this method turn() : 调用此方法turn()

     static int turn(int player) { ... } 

The stream pipeline now looks like this: 现在,流管道如下所示:

    IntStream.iterate(0, player -> (player + 1) % playerCount)
             .map(PigDice::turn)
             .filter(player -> player > -1)
             .findFirst()
             .ifPresent(
                player ->
                    System.out.printf("\n\nPlayer %d wins with a score of %d",
                        player, safeScore[player]));

The IntStream.iterate() method produces a stream of int values starting with the provided initial value, which is zero in this case. IntStream.iterate()方法生成一个以提供的初始值开头的int值流,在这种情况下,该初始值为零。 Subsequent values are computed by the lambda expression. 后续值由lambda表达式计算。 Here, that expression adds one and computes the remainder with playerCount , which is two in this example. 在这里,该表达式加1并使用playerCount计算余数,在本示例中为2。 The result is a stream of values 0, 1, 0, 1, 0, 1, ... representing the player number whose turn it is. 结果是一个值流0、1、0、1、0、1,...,表示轮到其的玩家编号。

The map() stage passes each of these values to the turn() method, which executes all the game logic. map()阶段将这些值中的每个传递给turn()方法,该方法执行所有游戏逻辑。 But if you boil down this logic, basically it returns -1 if there is no winner and it returns its input argument (the current player number) if that player has won. 但是,如果您简化此逻辑,则如果没有获胜者,则基本上返回-1;如果获胜者,则返回其输入参数(当前玩家编号)。 This results in a stream -1, -1, -1, -1, ... 0 if player 0 has won (or 1 for the last value if player 1 has won). 如果玩家0获胜,则流-1,-1,-1,-1,... 0(如果玩家1获胜,则最后一个值为1)。

The result stream from map() is only part of the story. map()的结果流只是故事的一部分。 The actual game logic operates by side effects on the game state, which is maintained in the captured variables scanner , random , score , and safeScore . 在实际的游戏逻辑由游戏状态,其被保持在所捕捉的变量副作用操作scannerrandomscore ,和safeScore

The filter() stage passes through only values that are greater than -1, thus it drops all those leading -1 values while the game is progressing, producing a value only after a player has won. filter()阶段仅通过大于-1的值,因此在游戏进行过程中它将丢弃所有这些前-1的值,仅在玩家获胜后才产生一个值。

The findFirst() stage takes the first element and then terminates the stream. findFirst()阶段获取第一个元素,然后终止流。 That's why the game eventually terminates. 这就是游戏最终终止的原因。

Now, findFirst() returns an OptionalInt which contains the number of the winning player. 现在, findFirst()返回一个OptionalInt ,其中包含获胜玩家的号码。 In general it could be empty, but in this case it never will be empty because iterate() produces an infinite stream. 通常,它可以为空,但是在这种情况下,它永远不会为空,因为iterate()会生成无限流。 Since it's never empty, the lambda expression inside of ifPresent() is always executed and is passed the number of the winning player; 由于永远不会为空,因此始终执行ifPresent()的lambda表达式,并将其传递给获胜玩家的号码; this prints out the final game result. 这会打印出最终的游戏结果。

That's basically how this works. 基本上就是这样。

Note that, as I and others have pointed out in comments, there are several bad code smells and anti-patterns here, plus a few bugs. 请注意,正如我和其他人在评论中指出的那样,这里有一些不良的代码味道和反模式,以及一些错误。 I strongly recommend not using this as an example of good lambda and streams coding practices. 我强烈建议不要将其用作良好的lambda和流编码实践的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以解释一下这个多态性的输出吗? - Can somebody please explain me this output of polymorphism? 有人可以向我解释一下此web.xml文件中发生了什么(安全性约束) - Can someone please explain to me what is happening in this web.xml file (security-constraints) 有人可以解释一下该程序在堆栈中的工作方式吗? - Can somebody explain me the working of this program with stacks? 有人可以解释一下下面的代码如何工作吗 - Could somebody please explain me how the following code actually works 编译错误-有人可以纠正我吗? - Compile error - can somebody please correct me? java 中的数据源是什么? 有人可以用简单的语言向我解释吗? - What is a datasource in java? Can someone please explain me in simple language? 有人可以告诉我这里的Java代码在做什么吗? - Can someone please explain to me what the java code here is doing? 谁能解释下面 for 循环中发生的事情? - Can anyone explain what's happening in below for loop? 有人可以解释一下这种休眠方法的作用吗? - Can somebody explain what this hibernate method does, 有人可以在曼哈顿为我解释java中的8个谜题吗? - Can somebody explain in Manhattan dstance for the 8 puzzle in java for me?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM