What is the generate() method of the Stream interface?
Overview
The generate() method of the Stream interface is used to generate an unlimited, unordered, sequential stream, with each element created by the supplied Supplier interface implementation. This may be used to create steady streams, streams with random components, and so forth.
Syntax
public static<T> Stream<T> generate(Supplier<? extends T> s)
Parameters
Supplier<? extends T> s: This is theSupplierinterface implementation.
Return value
The method returns an infinite, sequential, and unordered stream of values.
Code
The code below shows how we can use the generate() method.
import java.util.Random;import java.util.stream.Stream;class Main {public static void main(String[] args) {// Generate a stream of random double values of length 5 and printing it to the consoleStream.generate(new Random()::nextDouble).limit(5).forEach(System.out::println);}}
Explanation
- Lines 1-2: We import the relevant packages.
- Line 7: We generate a stream of random double values of length 5 and print it to the console.