adam bien's blog

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.