java - 如何打开流
问题描述
我想使用 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 的新手,所以我仍在学习它。你能帮助我吗?
解决方案
如果您想计算每个 的出现次数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>
所有Outcome
s 中的Round
一个。
推荐阅读
- java - 检查字符串是否按字母顺序排列
- node.js - express-validator :如何检查电子邮件 ID 数组?
- docker - 使用不同的文件运行 docker-compose up 会启动相同的数据库
- r - 如何将我的时间“箱”转换为连续的以在 R 中进行时间序列分析?
- python - 检测游戏中涉及旋转件的碰撞问题
- sql - 使用分层标准获取不同的值
- javascript - 如何在此代码博客模板代码中添加 Font Awesome 图标
- java - Java 编程项目
- python - 如何在 Python 中解压嵌套的 DBRef?
- pattern-matching - 模式匹配 SML 中的列表