Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
stream
generate

What is the generate() method of the Stream interface?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The generate() method of the Stream interface is used to generate an unlimited, unordered, sequential stream, with each element created by the supplied Supplier interface implementation. This may be used to create steady streams, streams with random components, and so forth.

Syntax

public static<T> Stream<T> generate(Supplier<? extends T> s)

Parameters

  • Supplier<? extends T> s: This is the Supplier interface implementation.

Return value

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

Code

The code below shows how we can use the generate() method.

import java.util.Random;
import java.util.stream.Stream;

class Main {
    public static void main(String[] args) {
        // Generate a stream of random double values of length 5 and printing it to the console
        Stream.generate(new Random()::nextDouble).limit(5).forEach(System.out::println);
    }
}
Implementation of the generate() method

Explanation

  • Lines 1-2: We import the relevant packages.
  • Line 7: We generate a stream of random double values of length 5 and print it to the console.

RELATED TAGS

java
communitycreator
stream
generate

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring