The Stream.generate()
method in Java is used to create an infinite stream of data, typically used when the programmer needs a limitless supply of data to be processed.
Here’s an example of how you might use Stream.generate()
:
package org.kodejava.util;
import java.util.stream.Stream;
public class StreamGenerate {
public static void main(String[] args) {
Stream<String> stringStream = Stream.generate(() -> "Hello, World!");
stringStream
.limit(5)
.forEach(System.out::println);
}
}
The output of this code snippet is:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
In this example, Stream.generate()
is used to create an infinite stream of the String "Hello, World!"
. The limit(5)
method is used to limit the infinite stream to just the first five elements, and forEach(System.out::println)
is used to print each of the first five elements to the console.
However, be careful while using Stream.generate()
without limit()
as it can lead to infinite loop. Generally, limit()
is used with Stream.generate()
to avoid this.
Here’s how you would use it with the Random
class to generate an infinite stream of random numbers:
package org.kodejava.util;
import java.util.Random;
import java.util.stream.Stream;
public class StreamGenerateRandomNumber {
public static void main(String[] args) {
Stream<Integer> randomNumbers = Stream.generate(new Random()::nextInt);
randomNumbers
.limit(10)
.forEach(System.out::println);
}
}
This will output something like:
-2134800739
730041861
357210260
1964364949
-1083197494
-1988345642
-1851656161
-562751737
-1777126198
-1030758565
In this case, new Random()::nextInt
is a supplier function that provides an infinite stream of random integers. The limit(10)
method is used to limit the stream to the first 10 random integers.