The Stream.generate()
method in Java is a powerful feature introduced in the java.util.stream.Stream
class. It allows you to create an infinite sequential unordered stream where each element is generated by a provided Supplier
. Let’s break it down:
- Purpose:
- The
Stream.generate(Supplier<T> s)
method creates an infinite stream of elements based on the providedSupplier
. - This is suitable for generating constant streams, streams of random elements, or any other custom sequence.
- The
- Method Signature:
static <T> Stream<T> generate(Supplier<T> s)
- Here:
Supplier<T>
is a functional interface representing a supplier of values.T
is the type of stream element.
- Here:
- Example 1: Generating a Stream of Random Integers:
import java.util.*;
import java.util.stream.Stream;
public class RandomIntegerStream {
public static void main(String[] args) {
Stream.generate(new Random()::nextInt).limit(5).forEach(System.out::println);
}
}
- Example 2: Generating a Stream of Random Doubles:
import java.util.*;
import java.util.stream.Stream;
public class RandomDoubleStream {
public static void main(String[] args) {
// Generate 8 random Double values
Stream.generate(new Random()::nextDouble) .limit(8) .forEach(System.out::println);
}
}
//Output: 0.5390254520295368 0.8477297185718798 0.23703352435894398 0.09156832989674057 0.9671295321757734 0.9989670394813547 0.8909416330715489 0.08177639888829968
In summary, Stream.generate()
provides a convenient way to create custom streams with dynamically generated elements. Whether you’re dealing with random data or other sequences, this method empowers you to work with infinite streams efficiently! 🚀