Search code examples
javajava-streamimmutability

Using streams to sum a collection of immutable `Duration` objects, in Java


The java.time.Duration class built into Java 8 and later represents a span of time unattached to the timeline on the scale of hour-minutes-seconds. The class offers a plus method to sum two such spans of time.

The java.time classes use immutable objects. So the Duration::plus method returns a new third Duration object as a result rather than altering (mutating) either of the input objects.

The conventional syntax to sum a collection of Duration objects would be the following.

Duration total = Duration.ZERO;
for ( Duration duration : durations )
{
    total = total.plus( duration );
}

Can streams be used in place of this for loop?


Solution

  • Stream#reduce

    This can be achieved using the overloaded Stream#reduce method that accepts an identity:

    durations.stream().reduce(Duration.ZERO, Duration::plus)
    

    The following snippet provides an example:

    var durations = List.of(Duration.ofDays(1), Duration.ofHours(1));
    System.out.println(durations.stream().reduce(Duration.ZERO, Duration::plus));
    

    As expected, the output is:

    PT25H