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 org.junit.Test;

public class RandomNumbersTest {

    public void streamNumbers() {

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

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:


You can just simply use
Random.ints(lower, upper)
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:
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:

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