In this section we will learn what the Stream generate() method is and how to use it in Java.
What is Java Stream generate() Method?
The Java Stream generate() method is used to generate an infinite number of stream elements.
Basically, this method takes a reference method and calls that all the times and a new element will be produced as a result of each call.
Note: inside this reference method is the place where we define what type of element and on what order should be produced.
Java generate() Method Syntax:
static <T> Stream<T> generate(Supplier<? extends T> s)
generate() Method Parameters:
The method has one parameter and that is of type Supplier which is a functional interface.
Basically, this means we need to pass a reference to a method as the argument of this generate() method.
Here’s the syntax of the reference method:
- It takes no argument.
- The method should return a value of a specific type.
Note: we can create this method using the lambda expression, or refer to an instance or static method that has the same signature.
generate() Method Return Value:
The return value of the method is a new stream.
Example: using Stream generate() method
import java.util.stream.Stream; import java.util.Random; class Main{ public static void main(String[] args) { Stream.generate(new Random()::nextInt).limit(10).forEach(e->System.out.println(e)); } }
Output:
-641638629 -1699779734 2070225514 -1503021894 -1532662826 -1106447102 1110343879 -1800622633 -2004554204 -1591735235