What is the generate() method of the DoubleStream interface?
The generate() method of the DoubleStream interface is used to generate an unlimited, unordered, and sequential stream, in which each element is created by the supplied DoubleSupplier interface implementation. This method may be used to create steady streams, streams with random values, and so on.
Syntax
public static DoubleStream generate(DoubleSupplier s)
Parameters
DoubleSupplier s: This is the implementation of the DoubleSupplier interface.
Return value
This method returns an infinite, sequential, and unordered stream of double values.
Code
The code given below shows us how we can use the generate() method:
import java.util.Random;import java.util.stream.DoubleStream;class Main {public static void main(String[] args) {DoubleStream doubleStream = DoubleStream.generate(() -> new Random().nextDouble());doubleStream.limit(5).forEach(System.out::println);}}
Explanation
- In lines 1 and 2, we import the
Randomclass and theDoubleStreaminterface. - In line 6, we generate a random stream of
doublevalues, using thegenerate()method and thenextDouble()method of theRandomclass. - In line 7, we limit the number of random generated
doublevalues to 5 and print the random generated values.