> 到地图,java,java-8,java-stream"/>

首页 > 解决方案 > 如何打开流> 到地图

问题描述

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

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

getRounds 返回一个 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<Outcome, Long> 缺少什么,我是 Java 和 Stream API 的新手,所以我仍在学习它。你能帮助我吗?

标签: javajava-8java-stream

解决方案


如果您想计算每个 的出现次数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())会给你Stream<Outcome>所有Outcomes 中的Round一个。


推荐阅读