java - 使用流添加持续时间的数组列表
问题描述
我有一个秒表类,可以测量生成报告所需的时间:
public class Stopwatch {
public String report;
public Instant startTime;
public Instant endTime;
public Duration duration;
}
在运行报告时,会收集时间和持续时间:
private ArrayList<Stopwatch> _reportStats;
最后,我想知道所有报告的总持续时间,例如:
Duration total = Duration.ZERO; // was null;
for (Stopwatch s: _reportStats) {
total = total.plus(s.duration);
}
除了我想使用流和减少,但我不能得到正确的语法:
Duration total = _reportStats.stream().reduce(... syntax ...);
解决方案
您可以reduce
将标识值 ( Duration.ZERO
) 用于 sum,并定义Duration.plus
为 accumulator :
Duration total = _reportStats.stream()
.map(Stopwatch::getDuration)
.reduce(Duration.ZERO, Duration::plus);
推荐阅读
- c# - 无法获取 OneDrive 文件夹的重新分析点信息
- php - 用php分割子串
- sql - 是否可以将子查询值用作 SELECT FIELD 和 FROM?
- laravel - Laravel 有没有像 IdentityServer4 这样的解决方案?
- php - PHP / FPDF:如何在单元格中插入图像?
- swift - 关闭 NSWindow 后 WKWebView 不回收
- android - PublishSubject 中的 Android RX Debance 一切,但首先
- excel - 使用 VBA 为图形着色
- java - 如何在存在事务的情况下使代码可重用成为可能?
- php - 使用 PHP 的 PDO 无法访问我的数据库