Stream generate() method in Java with examples

Stream generate(Supplier<T> s) 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.

Syntax :

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

Where, Stream is an interface and T
is the type of stream elements.
s is the Supplier of generated 
elements and the return value is
a new infinite sequential
unordered Stream.

Example 1 : To generate stream of random integer.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream.generate()
// to generate an infinite sequential
// unordered stream
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
      
    // using Stream.generate() method 
    // to generate 5 random Integer values
    Stream.generate(new Random()::nextInt)
    .limit(5).forEach(System.out::println); 
    }
}

chevron_right


Output :

697197501
50139200
321540264
1042847655
-770409472

Example 2 : To generate stream of random Double.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream.generate()
// to generate an infinite sequential
// unordered stream
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
      
    // using Stream.generate() method 
    // to generate 8 random Double values
    Stream.generate(new Random()::nextDouble)
    .limit(8).forEach(System.out::println); 
    }
}

chevron_right


Output :

0.5390254520295368
0.8477297185718798
0.23703352435894398
0.09156832989674057
0.9671295321757734
0.9989670394813547
0.8909416330715489
0.08177639888829968


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.