Java: An Endless List of Random Booleans

This snippet generates an endless / limited (to ten in this example) list of booleans:


import java.util.stream.Stream;
import java.util.stream.Collectors;

//...
var randomBooleans = Stream.
                    generate(Math::random).
                    limit(10).
                    map(r -> r > 0.5).
                    collect(Collectors.toList());

System.out.println(randomBooleans);

...or (thanks to @RUAmentalist):


import java.util.Random;
//...
var randomBooleans = new Random().
                    ints(10).
                    mapToObj(r -> r > 0.5).
                    collect(Collectors.toList());
System.out.println(randomBooleans);

Prints: [true, false, true, false, false.... The output should be different each time :-)

Comments:

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