Generating Pseudorandom Numbers with RandomGenerator Interface

The following example demonstrates the basic way to create a PRNG and use it to generate a random number:

        RandomGenerator random1 = RandomGenerator.of("Random");
        long value1 = random1.nextLong();
        System.out.println(value1);

It uses the method RandomGenerator.of(String). The argument of this method is the algorithm name of the PRNG. Java SE contains many PRNG classes. Unlike Random, however, most of them are in the jdk.random package.

The RandomGenerator interface contains many methods such as nextLong(), nextInt(), nextDouble(), and nextBoolean() to generate a random number of various primitive data types.

The following example demonstrates how to create a PRNG using the RandomGeneratorFactory class:

        RandomGeneratorFactory<RandomGenerator> factory2 =
            RandomGeneratorFactory.of("SecureRandom");
        RandomGenerator random2 = factory2.create();
        long value2 = random2.nextLong();
        System.out.println(value2); 

To obtain a list of PRNGs implemented by Java SE, call the RandomGeneratorFactory.all() method:

        RandomGeneratorFactory.all()
            .map(f -> f.name())
            .sorted()
            .forEach(n -> System.out.println(n));

This method returns a stream of all the available RandomGeneratorFactory instances available.

You can use the RandomGeneratorFactory class to create PRNGs based on characteristics other than an algorithm’s name. The following example finds the PRNG with the longest period, and creates a RandomGeneratorFactory based on this characteristic:

        RandomGeneratorFactory<RandomGenerator> greatest =
            RandomGeneratorFactory
                .all()
                .sorted((f, g) -> g.period().compareTo(f.period()))
                .findFirst()
                .orElse(RandomGeneratorFactory.of("Random"));
        System.out.println(greatest.name());
        System.out.println(greatest.group());
        System.out.println(greatest.create().nextLong());