Stream Random

Description

java.util.Random class provides ints(), longs(), and doubles() return infinite IntStream, LongStream, and DoubleStream, respectively.

Example

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


import java.util.Random;
/*from   w w  w .j av  a  2s . c om*/
public class Main {
  public static void main(String[] args) {
    new Random().ints()
    .limit(5)
    .forEach(System.out::println);

  }
}

The code above generates the following result.

Example 2

We can use the nextInt() method of the Random class as the Supplier in the generate() method to achieve the same.


import java.util.Random;
import java.util.stream.Stream;
/*from www  . java 2s . c  o m*/
public class Main {
  public static void main(String[] args) {
    Stream.generate(new Random()::nextInt)
    .limit(5)
    .forEach(System.out::println);
  }
}

The code above generates the following result.

Example 3

To work with only primitive values, use the generate() method of the primitive type stream interfaces.


import java.util.Random;
import java.util.stream.IntStream;
//from w  w  w.  ja  v  a  2s  .c om
public class Main {
  public static void main(String[] args) {
    IntStream.generate(new Random()::nextInt)
    .limit(5)
    .forEach(System.out::println);

  }
}

The code above generates the following result.

Example 4

To generate an infinite stream of a repeating value.


import java.util.stream.IntStream;
/* www. j  ava 2  s .  c  o  m*/
public class Main {
  public static void main(String[] args) {
    IntStream.generate(() ->  0)
    .limit(5)
    .forEach(System.out::println);
  }
}

The code above generates the following result.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial