Java Stream generate() method with example

Stream interface provides a method with following signature:

static <T> Stream<T> generate(Supplier<T> s)

This method returns an infinite sequential unordered stream where each element is generated by the provided Supplier.

This is suitable for generating constant streams, streams of random elements, etc.

This method generates an infinite stream. We can add limit to get desired number of elements.

// Java code Stream.generate() example

import java.util.Random;
import java.util.stream.Stream; 
public class StreamGenerateExample { 
    public static void main(String[] args) { 
    // Stream.generate() method example  
    // to generate 5 random Integer values 
    Stream.generate(new Random()::nextInt)