Stream.generate() uses a given supplier (a function without arguments) to produce an infinite stream of values. Unlike iterate(), each new element is produced independently rather than based on the previous element.
1 . Generating a Constant Value
In this example, we create a stream that repeatedly outputs the same string. We then limit the stream so that only five copies are printed
import java.util.stream.Stream;
public class GenerateBasicExample {
public static void main(String[] args) {
// Generate a stream where each element is "Hello Java".
Stream<String> constantStream = Stream.generate(() -> "Hello Java");
// Limit the stream to 5 elements and print them.
constantStream.limit(5).forEach(System.out::println);
}
}
Explanation: The supplier (() -> "Hello Java") is called repeatedly to produce each element in the stream. The stream would be infinite if not for limit(5).
Output::
Hello Java
Hello Java
Hello Java
Hello Java
Hello Java
2 .
Generating Random Numbers
This example makes use of the built-in Math.random() method as a supplier to generate random numbers. Again, we limit the stream so it outputs a finite number of elements.
import java.util.stream.Stream;
public class RandomNumbersGenerate {
public static void main(String[] args) {
// Generate an infinite stream of random double values.
Stream<Double> randomNumbers = Stream.generate(Math::random);
// Limit to 5 random numbers and print each.
randomNumbers.limit(5).forEach(System.out::println);
}
}
Explanation: Math::random is a method reference that supplies a new random double (between 0.0 and 1.0) each time it is called. The stream is limited to 5 elements.
Output: The output will be 5 random double numbers, for example:
0.23744893145251387
0.8912345123451234
0.11234567890123456
0.6734523981274352
0.5493827459812739
No comments:
Post a Comment