如何使用Java 8 Stream API转换代码?

Man*_*gos 3 java java-8 java-stream

我正在编写一种简单的方法来打印一系列游戏结果的统计数据。每个游戏都有一个结果列表,其中包含根据游戏结果列出的枚举。我的老师在我的代码中注释了一个TODO:

public static void printStatistics(List<Game> games) {
    float win = 0;
    float lose = 0;
    float draw = 0;
    float all = 0;

    //TODO: should be implemented /w stream API
    for (Game g : games) {
        for (Outcome o : g.getOutcomes()) {
            if (o.equals(Outcome.WIN)) {
                win++;
                all++;
            } else if (o.equals(Outcome.LOSE)) {
                lose++;
                all++;
            } else {
                draw++;
                all++;
            }
        }
    }
    DecimalFormat statFormat = new DecimalFormat("##.##");

    System.out.println("Statistics: The team won: " + statFormat.format(win * 100 / all) + " %, lost " + statFormat.format(lose * 100 / all)
            + " %, draw: " + statFormat.format(draw * 100 / all) + " %");

}
Run Code Online (Sandbox Code Playgroud)

我熟悉lambda表达式。我尝试在网上寻找解决方案,但找不到流访问类的字段的示例。如果您可以给我解决方案,或者提供相关的教程,我将非常高兴。谢谢。

shm*_*sel 5

您可以将游戏,flatMap流化为结果,然后将它们收集到计数图中:

Map<Outcome, Long> counts = games.stream()
        .map(Game::getOutcomes)
        .flatMap(Collection::stream)
        .collecting(Collectors.groupingBy(o -> o, Collectors.counting()));

long win = counts.getOrDefault(Outcome.WIN, 0L);
long lose = counts.getOrDefault(Outcome.LOSE, 0L);
long draw = counts.getOrDefault(Outcome.DRAW, 0L);
long all = games.stream()
        .mapToInt(g -> g.getOutcomes().size())
        .sum();
Run Code Online (Sandbox Code Playgroud)