Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 712
Basil Bourque Avatar asked Mar 23 '20 15:03

Basil Bourque


People also ask

How should we end the stream to calculate sum of elements?

Using IntStream. The Stream API provides us with the mapToInt() intermediate operation, which converts our stream to an IntStream object. This method takes a mapper as a parameter, which it uses to do the conversion, then we can call the sum() method to calculate the sum of the stream's elements.

What is the difference between stream () and Parallelstream ()?

A sequential stream is executed in a single thread running on one CPU core. The elements in the stream are processed sequentially in a single pass by the stream operations that are executed in the same thread. A parallel stream is executed by different threads, running on multiple CPU cores in a computer.

Are streams immutable in Java?

A stream cannot modify the underlying collection (if the collection itself is not exposed), so elements cannot be added or removed, nor can the order be changed.

What is the easiest way to print the sum of all of the numbers present in a list using Java 8?

We generally iterate through the list when adding integers in a range, but java. util. stream. Stream has a sum() method that when used with filter() gives the required result easily.

Which method can collect a stream in a custom collection?

toMap() The toMap collector can be used to collect Stream elements into a Map instance.

What does stream () Do Java?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

Which stream operations are needed to get sum of all even numbers from stream of integer values?

stream(). mapToInt( Integer::intValue ). sum() .

Are streams faster in Java?

Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.

Why streams are lazy in Java?

Streams are lazy because intermediate operations are not evaluated until terminal operation is invoked. Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream. The pipeline accumulates these newly created streams.

Can Java stream be used multiple times?

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream.


2 Answers

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
like image 135
Jacob G. Avatar answered Oct 04 '22 00:10

Jacob G.


Yes, you can make use of reduce operation with identity element as

Duration total = durations.stream()
        .reduce(Duration.ZERO, Duration::plus);
like image 43
Naman Avatar answered Oct 04 '22 00:10

Naman