gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:07:16 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com