Java - Generate Random numbers in Stream


Java Random class in the java.util package has methods to work with streams.

Methods like ints(), longs(), and doubles() return infinite IntStream, LongStream, and DoubleStream, respectively, which contain random numbers of the int, long, and double types.

The following code prints five random int values from an IntStream returned from the ints() method of the Random class:


import java.util.Random;

public class Main {
  public static void main(String[] args) {
    // Print five random integers
    new Random().ints().limit(5).forEach(System.out::println);
  }/* www .  ja  va  2s  .  co m*/


Related Topic