Java 8: An Endless Stream Of Random Numbers

The method Math#random is a Supplier<double> and can be used to generate an endless Stream or random numbers:


import java.util.stream.Stream;
import org.junit.Test;

public class RandomNumbersTest {

    @Test
    public void streamNumbers() {
        randomStream(10).
                limit(10).
                forEach(System.out::println);
    }


    public Stream<Long> randomStream(int range) {
        return Stream.generate(Math::random).
                map(n -> n * range).
                map(Math::round);
    }
}

The unit test above generates:

5 4 2 9 8 9 9 0 9 8

(...hopefully a different sequence on your machine :-))

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

Comments:

You can just simply use
Random.ints(lower, upper)
or
Random.longs(lower, upper)
which generates IntStream and LongStream respectively. The streams can be then boxed if needed.

Posted by airborn on March 07, 2017 at 10:59 AM CET #

Java 8 actually added methods doubles(), ints() and longs() to Random which produce streams of random numbers:
https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#method.summary
Great minds think alike? ;-)

For example:
int limit = 10;
int fromInclusive = 0;
int toExclusive = 11;
new Random().longs(limit, fromInclusive, toExclusive).forEach(System.out::println);

Also I believe there's a problem in your example with Math.round():
The intervals that are rounded to the boundary values 0 and 10 are only half as wide as the intervals that are rounded to non-boundary values. Which means boundary values have a lower probability. Ie
- [0,0.5) is rounded to 0
- [0.5,1.5) is rounded to 1

Posted by Arend v. Reinersdorff on March 08, 2017 at 10:23 PM CET #

What about java.util.Random and it's ints() method which already does this?!?!

Posted by Deven Phillips on March 14, 2017 at 02:34 PM CET #

There's a method in java.util.Random as well for generating a stream of random integers in a given range:
https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#ints-long-int-int-

Posted by Jimmy Praet on March 15, 2017 at 08:42 PM CET #

Streams can also be get from java.util.Random directly using e.g.:
doubles(), ints() and so on.

Posted by Tobias on May 15, 2017 at 09:56 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License