What is the generate() method of the IntStream interface in Java?

Overview

The generate() method of the IntStream interface is used to generate an unlimited, unordered, and sequential stream, wherein each element is created by the supplied IntSupplier interface implementation. The IntSupplier interface implementation may also be used to create steady streams, streams with random values, and so on.

Syntax

The syntax of the generate method is given below:

public static IntStream generate(IntSupplier s)

Parameters

  • IntSupplier s: The IntSupplier interface implementation.

Return value

This method returns an infinite, sequential, and unordered stream of integer values.

Code

import java.util.Random;
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
IntStream intStream = IntStream.generate(() -> new Random().nextInt());
intStream.limit(5).forEach(System.out::println);
}
}

Code explanation

  • In lines 1 and 2, we import the Random class and the IntStream interface.
  • In line 6, we use the generate() and nextInt() methods of the Random class to generate a random stream of integer values.
  • In line 7, we limit the number of generated random integer values to 5 and print the generated random values.

Free Resources