首页 > 解决方案 > 使用流添加持续时间的数组列表

问题描述

我有一个秒表类,可以测量生成报告所需的时间:

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 ...);

标签: javajava-stream

解决方案


您可以reduce标识值 ( Duration.ZERO) 用于 sum,并定义Duration.plus为 accumulator :

Duration total = _reportStats.stream()
        .map(Stopwatch::getDuration)
        .reduce(Duration.ZERO, Duration::plus);

推荐阅读