Java Stream generate() Method Tutorial

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.Random;
class Main{
    public static void main(String[] args) {
        Stream.generate(new Random()::nextInt).limit(10).forEach(e->System.out.println(e));












Top Technologies