Which method of the stream class can be used to create infinite streams?

1 Answers
Answered by suresh

Answer:

To create infinite streams in Java, you can use the generate() method of the Stream class. This method takes a Supplier functional interface as a parameter and generates an infinite stream of elements by calling the get() method of the supplier.

Here's an example of how you can use the generate() method to create an infinite stream:

```java
import java.util.stream.Stream;
import java.util.function.Supplier;

public class InfiniteStreamExample {
public static void main(String[] args) {

Supplier supplier = () -> {
return (int) (Math.random() * 100);
};

Stream infiniteStream = Stream.generate(supplier);

infiniteStream.limit(10).forEach(System.out::println);
}
}
```

In this example, we create an infinite stream of random integers between 0 and 100 using the generate() method. We then limit the stream to print only the first 10 elements.

Using the generate() method is a convenient way to create infinite streams in Java for tasks such as generating random numbers, iterating over a sequence, or creating sequences with specific rules.

Answer for Question: Which method of the stream class can be used to create infinite streams?