How do I generate random alphanumeric strings?

The following code snippet demonstrates how to use RandomStringGenerator class from the Apache Commons Text library to generate random strings. To create an instance of the generator we can use the RandomStringGenerator.Builder() class build() method. The builder class also helps us to configure the properties of the generator. Before calling the build() method we can set the properties of the builder using the following methods:

  • withinRange() to specifies the minimum and maximum code points allowed in the generated string.
  • filteredBy() to limits the characters in the generated string to those that match at least one of the predicates supplied. Some enum for the predicates: CharacterPredicates.DIGITS, CharacterPredicates.LETTERS.
  • selectFrom() to limits the characters in the generated string to those who match at supplied list of Character.
  • usingRandom() to overrides the default source of randomness.

After configuring and building the generator based the properties defined, we can generate the random strings using the generate() methods of the RandomStringGenerator. There are two methods available:

  • generate(int length) generates a random string, containing the specified number of code points.
  • generate(int minLengthInclusive, int maxLengthInclusive) generates a random string, containing between the minimum (inclusive) and the maximum (inclusive) number of code points.

And here is your code snippet:

package org.kodejava.commons.text;

import org.apache.commons.text.CharacterPredicates;
import org.apache.commons.text.RandomStringGenerator;

public class RandomStringDemo {
    public static void main(String[] args) {
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
                .withinRange('0', 'z')
                .filteredBy(CharacterPredicates.DIGITS, CharacterPredicates.LETTERS)
                .build();

        for (int i = 0; i < 10; i++) {
            System.out.println(generator.generate(10, 20));
        }
    }
}

Below are examples of generated random alphanumeric strings:

weJDtVARLIFS96WXje
FYrNzTR3Q3dUrLT3Xsc
4F1fu8nSsA
nIQi3a4Oyv9
l6QcsP9bejdbaLd2jd
Cc9YgTfgwo
2B8un8YCcxn9m2
RAN2dZAWalUIWeZeoS
jPQspicyaKfAzS14twH
GTurc0lWkSid03rG0JZ

Apache Logo

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.