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
Maven Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.12.0</version>
</dependency>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024