Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
generate
longstream

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

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.

Answers Code

The generate() method of the LongStream interface is used to generate an unlimited, unordered, and sequential stream. Each element is created by the supplied LongSupplier interface implementation. We can use that to create steady streams, streams with random values, and so forth.

Syntax

public static LongStream generate(LongSupplier s)

Parameters

  • LongSupplier s: This is the implementation of the LongSupplier interface.

Return value

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

Code

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

Explanation

  • Lines 1 and 2: We import the Random class and the LongStream interface.

  • Line 6: We generate a random stream of long values using the generate() method and the nextLong() method of the Random class.

  • Line 7: We limit the number of generated random long values to 5 and print the generated random values.

RELATED TAGS

java
communitycreator
generate
longstream

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.

Answers Code
Keep Exploring