In  this tutorial, we will see “How to generate Infinite stream of values using Java 8?”Generate infinite stream of values in java 8

 

In Java 8, the Stream.generate() method can be used to generate an infinite stream of values. This method takes a Supplier<T> as an argument which is a functional interface that defines a method get() that generates the next value in the stream.

Java 8 – How to Generate Infinite Stream of Values? Click To Tweet

Using below example, learn how generate() method can be used to generate an infinite stream of random numbers:

 

Output:

check if text or string present in a file using java 8

In the above example, random::nextDouble is a method reference to the nextDouble() method of the Random class, which creates a random double value between 0.0 and 1.0.

In order to limit the stream to a specific value then limit() method can be used:

 

Output:

find second largest number in an array using java 8 stream

Using above example, we can create a stream of random double values  limited to ‘5’.

For your information, let me share that ‘generate’ method can be used to create a stream of any type of elements.

skip method java 8 stream

Generate infinite stream of values in java 8

Using above code, you can create a stream of 5 Strings with value “test”.

Java 8 – How to Generate Infinite Stream of Values? Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: