gpt4 book ai didi

java - 如何使用 Java 8 流 API 转换我的代码?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:38 25 4
gpt4 key购买 nike

我正在编写一个简单的方法来打印一系列游戏结果的统计数据。每个游戏都有一个结果列表,其中包含根据游戏结果的枚举。我的讲师在我的代码中评论了一个 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) + " %");

}

我熟悉 lambda 表达式。我试着在网上寻找解决方案,但找不到流访问类字段的字段的示例。如果你能给我一个解决方案,或者提供相关教程,我将很高兴。谢谢。

最佳答案

您可以流式传输游戏,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();

关于java - 如何使用 Java 8 流 API 转换我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54992023/

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