java - 使用流添加持续时间的数组列表

标签 java java-stream

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

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

最佳答案

您可以使用 reduceidentity 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/

相关文章:

java - 在Java中使用Stream迭代斐波那契数列

java - 在消费者方法中创建的 Lambda Collect 元素

java - Java 8 findFirst().isPresent() 是否比 count() > 0 更有效?

java - 不能从 Collectors.toMap 中的静态上下文引用非静态方法

java - 从 MDC 中清除 requestId 的位置

java - 带循环的输入和输出

lambda - Java 8嵌套流

java - JavaFX 的奇怪 Gluon 项目结构 - Android 移植

java - 如何用不在空白处的字符串拆分 a

java - 为什么特征方法为 Collector 返回一个枚举而为 Spliterator 返回一个 int?