如何将 Stream<Map<Outcome, Long>> 转换为 Map<Outcome, Long>

How to turn Stream<Map<Outcome, Long>> to Map<Outcome, Long>

我想使用 Java Stream API 来重构这段代码:

for (Round round : dataStore.getRounds()) {
            Map<Outcome, Long> outcomes = round.getOutcomes()
                    .stream()
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}

getRounds returns 一个 Round 对象列表,每个 Round 都有一个 Outcome 列表,其中 Outcome 是一个枚举。我设法做到了这一点:

Stream<Map<Outcome, Long>> out = dataStore.getRounds()
                .stream()
                .map(round -> round.getOutcomes()
                        .stream()
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())));

我无法弄清楚将其转换为 Map 缺少什么,我是 Java 和 Stream API 的新手,所以我仍然学习它。你能帮帮我吗?

如果你想计算每个 Outcome 出现的次数,你应该使用 flatMap 而不是 map:

Map<Outcome, Long> out =
    dataStore.getRounds()
             .stream()
             .flatMap(round -> round.getOutcomes().stream())
             .collect(Collectors.groupingBy(Function.identity(), 
                                            Collectors.counting()));

.flatMap(round -> round.getOutcomes().stream()) 将为您提供所有 Round 的所有 Outcome 中的单个 Stream<Outcome>