✅ Example using Stream.generate()
import java.util.Random;
import java.util.stream.Stream;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
Stream.generate(() -> random.nextInt(100)) // generate infinite stream of random ints (0–99)
.limit(10) // take only the first 10
.forEach(System.out::println); // print each number
}
}
🔹 Breakdown:
Stream.generate(...)
: creates an infinite streamrandom.nextInt(100)
: generates a random number between0
and99
limit(10)
: keeps only the first 10forEach(...)
: prints them one by one
✅ Sample Output:
23
87
45
2
71
...
In parallel it will be like this
import java.util.Random;
import java.util.stream.Stream;
public class ParallelRandomExample {
public static void main(String[] args) {
Random random = new Random();
Stream.generate(() -> random.nextInt(100))
.limit(10)
.parallel() // make the stream parallel
.forEach(System.out::println); // print (order not guaranteed)
}
}