Adam Bien's Weblog

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.


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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