Learnitweb

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) 
    .limit(5).forEach(System.out::println);  
    } 
} 

Output

-545094256
-717482304
-2017710222
323267085
1220315287