src/share/classes/java/util/Random.java

Print this page
rev 7020 : 8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
Contributed-by: akhil.arora@oracle.com, brian.goetz@oracle.com

@@ -24,10 +24,14 @@
  */
 
 package java.util;
 import java.io.*;
 import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
 import sun.misc.Unsafe;
 
 /**
  * An instance of this class is used to generate a stream of
  * pseudorandom numbers. The class uses a 48-bit seed, which is

@@ -511,10 +515,63 @@
             return v1 * multiplier;
         }
     }
 
     /**
+     * Returns a stream of pseudorandom, uniformly distributed
+     * {@code integer} values from this random number generator's
+     * sequence. Values are obtained as needed by calling
+     * {@link #nextInt()}.
+     *
+     * @return an infinite stream of {@code integer} values
+     * @since 1.8
+     */
+    public IntStream ints() {
+        return IntStream.generate(this::nextInt);
+    }
+
+    /**
+     * Returns a stream of pseudorandom, uniformly distributed
+     * {@code long} values from this random number generator's
+     * sequence. Values are obtained as needed by calling
+     * {@link #nextLong()}.
+     *
+     * @return an infinite stream of {@code long} values
+     * @since 1.8
+     */
+    public LongStream longs() {
+        return LongStream.generate(this::nextLong);
+    }
+
+    /**
+     * Returns a stream of pseudorandom, uniformly distributed
+     * {@code double} values between {@code 0.0} and {@code 1.0}
+     * from this random number generator's sequence. Values are
+     * obtained as needed by calling {@link #nextDouble()}.
+     *
+     * @return an infinite stream of {@code double} values
+     * @since 1.8
+     */
+    public DoubleStream doubles() {
+        return DoubleStream.generate(this::nextDouble);
+    }
+
+    /**
+     * Returns a stream of pseudorandom, Gaussian ("normally")
+     * distributed {@code double} values with mean {@code 0.0}
+     * and standard deviation {@code 1.0} from this random number
+     * generator's sequence. Values are obtained as needed by
+     * calling {@link #nextGaussian()}.
+     *
+     * @return an infinite stream of {@code double} values
+     * @since 1.8
+     */
+    public DoubleStream gaussians() {
+        return DoubleStream.generate(this::nextGaussian);
+    }
+
+    /**
      * Serializable fields for Random.
      *
      * @serialField    seed long
      *              seed for random computations
      * @serialField    nextNextGaussian double