Listing the Available Random Algorithms

System.out.printf("%-13s| %s\n-------------|---------------------\n", "Group", "Name");
java.util.random.RandomGeneratorFactory.all()
        .sorted(java.util.Comparator.comparing(java.util.random.RandomGeneratorFactory::name))
        .forEach(factory -> System.out.printf("%-13s| %s\n", factory.group(), factory.name()));

The output is similar to the following:

Group        | Name
-------------|---------------------
LXM          | L128X1024MixRandom
LXM          | L128X128MixRandom
LXM          | L128X256MixRandom
LXM          | L32X64MixRandom
LXM          | L64X1024MixRandom
LXM          | L64X128MixRandom
LXM          | L64X128StarStarRandom
LXM          | L64X256MixRandom
Legacy       | Random
Legacy       | SecureRandom
Legacy       | SplittableRandom
Xoroshiro    | Xoroshiro128PlusPlus
Xoshiro      | Xoshiro256PlusPlus

Check from the following address on how to choose which algorithm to choose:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/random/package-summary.html#algorithms

Creating an instance of RandomGenerator

The default algorithm (i.e. L32X64MixRandom)

var generator = java.util.random.RandomGenerator.getDefault();

The specific algorithm (e.g. L64X128MixRandom)

var generator = java.util.random.RandomGenerator.of("L64X128MixRandom");

Use the static method RandomGenerator.of and pass the name of the algorithm.

Generating Random Number

Use one of the following instance methods of the RandomGenerator class:

  • nextDouble()
  • nextDouble(double bound)
  • nextDouble(double origin, double bound)
  • nextFloat()
  • nextFloat(float bound)
  • nextFloat(float origin, float bound)
  • nextInt()
  • nextInt(int bound)
  • nextInt(int origin, int bound)
  • nextLong()
  • nextLong(long bound)
  • nextLong(long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

 var generator = java.util.random.RandomGenerator.of("Random");
 System.out.println(generator.nextInt());

The output is a random integer number.

Generating Random Number Using Streams

Use one of the following instance methods of RandomGenerators class to create streams:

  • doubles()
  • doubles(double origin, double bound)
  • doubles(long streamSize)
  • doubles(long streamSize, double origin, double bound)
  • ints()
  • ints(int origin, int bound)
  • ints(long streamSize)
  • ints(long streamSize, int origin, int bound)
  • longs()
  • longs(long origin, long bound)
  • longs(long streamSize)
  • longs(long streamSize, long origin, long bound)

The origin parameter is inclusive and bound parameter is exclusive.

Example using a classic random algorithm

var generator = java.util.random.RandomGenerator.of("Random");
var randomInt = generator.ints(100, 1, 100)
        .filter(number -> number % 2 == 0 )
        .findFirst();
randomInt.ifPresent(System.out::println);

The output is a random integer number.