我有一个秒表类,用于测量生成报告所需的时间:
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);
}
除了我想使用一个流和一个 reduce 但我无法获得正确的语法:
Duration total = _reportStats.stream().reduce(... syntax ...);
最佳答案
您可以使用 reduce
和 identity value (Duration.ZERO
) 求和,并定义 Duration.plus
作为累加器:
Duration total = _reportStats.stream()
.map(Stopwatch::getDuration)
.reduce(Duration.ZERO, Duration::plus);
关于java - 使用流添加持续时间的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853035/