Java 使用流添加持续时间的arraylist
我有一个秒表课程,用于测量生成报告所需的时间:Java 使用流添加持续时间的arraylist,java,java-stream,Java,Java Stream,我有一个秒表课程,用于测量生成报告所需的时间: public class Stopwatch { public String report; public Instant startTime; public Instant endTime; public Duration duration; } 运行报告时,将收集计时和持续时间: private ArrayList<Stopwatch> _reportStats; 除了我想使用流和reduce,但我无法获得正确的
public class Stopwatch {
public String report;
public Instant startTime;
public Instant endTime;
public Duration duration;
}
运行报告时,将收集计时和持续时间:
private ArrayList<Stopwatch> _reportStats;
除了我想使用流和reduce,但我无法获得正确的语法:
Duration total = _reportStats.stream().reduce(... syntax ...);
您可以使用
reduce
和标识值(Duration.ZERO
)作为sum,并将Duration.plus定义为累加器:
Duration total = _reportStats.stream()
.map(Stopwatch::getDuration)
.reduce(Duration.ZERO, Duration::plus);
谢谢,主要的问题是我缺少了映射(object->object.field)
,就像你在那里看到的那样Stopwatch::getDuration
Duration total = _reportStats.stream()
.map(Stopwatch::getDuration)
.reduce(Duration.ZERO, Duration::plus);