Generate Infinite Stream of Doubles in Java

This article provides an overview of how to generate infinite stream of doubles in Java. An infinite stream is a sequential, unordered Stream that doesn’t end.


Until now, many of you might have operated only on the finite streams. If a Stream in Java is not properly bounded, then calling any terminal operation upon it may cause the program to enter into an infinite loop.

We should always ensure that a Stream is properly bounded. If not, then we should limit the stream to only return first few terms from the beginning. Let’s now discuss how to generate infinite stream of doubles in Java:


1. DoubleStream.iterate()

DoubleStream.iterate() method accepts two parameters – a seed which would be the first term in the Stream, and a function to be applied to the previous term of the Stream to produce the value of next term in the Stream.


2. DoubleStream.generate()

Another alternative is to use DoubleStream.generate() method that returns an infinite stream. It accepts a Supplier<T> to generate new values, rather than a function. There are lots of suppliers available in Java that can be passed as an parameter to the DoubleStream.generate() method to generate an infinite stream of doubles as shown below.


2.1. Using Math.random()


2.2. Random.nextDouble()


2.3. ThreadLocalRandom.current().nextDouble()


2.4. PrimitiveIterator.OfDouble nextDouble()


3. Random.doubles()

Finally, we can also use Random.doubles() method to generate a stream of pseudorandom doubles:

We can also specify the range of returned random values as shown below.


Exercise: Create an Infinite Stream of Integers in Java.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of