Java.Java8.How can I display 10 random numbers using forEach()?

✅ 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 stream
  • random.nextInt(100): generates a random number between 0 and 99
  • limit(10): keeps only the first 10
  • forEach(...): 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)
    }
}
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.