javajava-stream

Adding an arraylist of durations using stream


I have a stopwatch class that measures the time it takes to produce reports:

public class Stopwatch {
  public String report;
  public Instant startTime;
  public Instant endTime;
  public Duration duration;
}

While reports are run the timings and duration are gathered:

private ArrayList<Stopwatch> _reportStats;

In the end I'd like to know the total duration for all the reports such as:

Duration total = Duration.ZERO; // was null;
for (Stopwatch s: _reportStats) {
  total = total.plus(s.duration);
}

Except I'd like to use a stream and a reduce but I can't get the syntax correct:

Duration total = _reportStats.stream().reduce(... syntax ...);

Solution

  • You can use reduce with an identity value (Duration.ZERO) for sum, and define Duration.plus as the accumulator :

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