Top Description Inners Fields Constructors Methods
org.apache.commons.text

public final Class RandomStringGenerator

extends Object
Class Inheritance
Imports
java.util.ArrayList, .Collections, .HashSet, .List, .Set, java.util.concurrent.ThreadLocalRandom, java.util.function.IntUnaryOperator, org.apache.commons.lang3.ArrayUtils, .StringUtils, .Validate

Generates random Unicode strings containing the specified number of code points. Instances are created using a builder class, which allows the callers to define the properties of the generator. See the documentation for the Builder class to see available properties.
// Generates a 20 code point string, using only the letters a-z
RandomStringGenerator generator = RandomStringGenerator.builder().withinRange('a', 'z').build();
String randomLetters = generator.generate(20);
// Using Apache Commons RNG for randomness
UniformRandomProvider rng = RandomSource.create(...);
// Generates a 20 code point string, using only the letters a-z
RandomStringGenerator generator = RandomStringGenerator.builder()
    .withinRange('a', 'z')
    .usingRandom(rng::nextInt)
    .build();
String randomLetters = generator.generate(20);

RandomStringGenerator instances are thread-safe when using the default random number generator (RNG). If a custom RNG is set by calling the method Builder.usingRandom(TextRandomProvider), thread-safety must be ensured externally.

Since
1.1

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static class
RandomStringGenerator.Builder

References Deprecated Builder is deprecated or references (maybe indirectly) at least one deprecated element.
A builder for generating RandomStringGenerator instances.

Field Summary

Modifier and TypeField and Description
private final List<Character>
characterList

The source of provided characters.

private final Set<CharacterPredicate>
inclusivePredicates

Filters for code points.

private final int
maximumCodePoint

The largest allowed code point (inclusive).

private final int
minimumCodePoint

The smallest allowed code point (inclusive).

private final IntUnaryOperator
random

The source of randomness for this generator.

Constructor Summary

AccessConstructor and Description
private
RandomStringGenerator(final RandomStringGenerator.Builder builder)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Constructs the generator.

Method Summary

Modifier and TypeMethod and Description
public static RandomStringGenerator.Builder

Returns:

a new builder.
builder
()
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Constructs a new builder.

public String

Returns:

The generated string.
generate
(final int
the number of code points to generate.
length
)

Generates a random string, containing the specified number of code points.

public String

Returns:

The generated string.
generate
(final int
the minimum (inclusive) number of code points to generate.
minLengthInclusive
,
final int
the maximum (inclusive) number of code points to generate.
maxLengthInclusive
)

Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive) number of code points.

private int

Returns:

The random number.
generateRandomNumber
(final int
the minimum value allowed.
minInclusive
,
final int
the maximum value allowed.
maxInclusive
)

Generates a random number within a range, using a ThreadLocalRandom instance or the user-supplied source of randomness.

private int

Returns:

The random number.
generateRandomNumber
(final List<Character>
predefined char list.
characterList
)

Generates a random number within a range, using a ThreadLocalRandom instance or the user-supplied source of randomness.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

characterListback to summary
private final List<Character> characterList

The source of provided characters.

inclusivePredicatesback to summary
private final Set<CharacterPredicate> inclusivePredicates

Filters for code points.

maximumCodePointback to summary
private final int maximumCodePoint

The largest allowed code point (inclusive).

minimumCodePointback to summary
private final int minimumCodePoint

The smallest allowed code point (inclusive).

randomback to summary
private final IntUnaryOperator random

The source of randomness for this generator.

Constructor Detail

RandomStringGeneratorback to summary
private RandomStringGenerator(final RandomStringGenerator.Builder builder)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Constructs the generator.

Method Detail

builderback to summary
public static RandomStringGenerator.Builder builder()

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Constructs a new builder.

Returns:RandomStringGenerator.Builder

a new builder.

Since
1.11.0
generateback to summary
public String generate(final int length)

Generates a random string, containing the specified number of code points.

Code points are randomly selected between the minimum and maximum values defined in the generator. Surrogate and private use characters are not returned, although the resulting string may contain pairs of surrogates that together encode a supplementary character.

Note

the number of char code units generated will exceed length if the string contains supplementary characters. See the Character documentation to understand how Java stores Unicode values.

Parameters
length:int

the number of code points to generate.

Returns:String

The generated string.

Exceptions
IllegalArgumentException:
if length < 0.
generateback to summary
public String generate(final int minLengthInclusive, final int maxLengthInclusive)

Generates a random string, containing between the minimum (inclusive) and the maximum (inclusive) number of code points.

Parameters
minLengthInclusive:int

the minimum (inclusive) number of code points to generate.

maxLengthInclusive:int

the maximum (inclusive) number of code points to generate.

Returns:String

The generated string.

Exceptions
IllegalArgumentException:
if minLengthInclusive < 0, or maxLengthInclusive < minLengthInclusive.
Since
1.2
See Also
RandomStringGenerator#generate(int)
generateRandomNumberback to summary
private int generateRandomNumber(final int minInclusive, final int maxInclusive)

Generates a random number within a range, using a ThreadLocalRandom instance or the user-supplied source of randomness.

Parameters
minInclusive:int

the minimum value allowed.

maxInclusive:int

the maximum value allowed.

Returns:int

The random number.

generateRandomNumberback to summary
private int generateRandomNumber(final List<Character> characterList)

Generates a random number within a range, using a ThreadLocalRandom instance or the user-supplied source of randomness.

Parameters
characterList:List<Character>

predefined char list.

Returns:int

The random number.

org.apache.commons.text back to summary

public Class RandomStringGenerator.Builder

extends Object
implements Builder<RandomStringGenerator>
Class Inheritance
All Implemented Interfaces
org.apache.commons.text.Builder, java.util.function.Supplier

References Deprecated

Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

A builder for generating RandomStringGenerator instances.

The behavior of a generator is controlled by properties set by this builder. Each property has a default value, which can be overridden by calling the methods defined in this class, prior to calling build().

All the property setting methods return the Builder instance to allow for method chaining.

The minimum and maximum code point values are defined using withinRange(int, int). The default values are 0 and Character#MAX_CODE_POINT respectively.

The source of randomness can be set using usingRandom(TextRandomProvider), otherwise ThreadLocalRandom is used.

The type of code points returned can be filtered using filteredBy(CharacterPredicate...), which defines a collection of tests that are applied to the randomly generated code points. The code points will only be included in the result if they pass at least one of the tests. Some commonly used predicates are provided by the CharacterPredicates enum.

This class is not thread safe.

Since
1.1

Field Summary

Modifier and TypeField and Description
private boolean
accumulate

Whether calls accumulates the source of provided characters.

private Set<Character>
characterSet

The source of provided characters.

public static final int
DEFAULT_LENGTH

The default string length produced by this builder: .

public static final int
DEFAULT_MAXIMUM_CODE_POINT

The default maximum code point allowed: Character#MAX_CODE_POINT ().

public static final int
DEFAULT_MINIMUM_CODE_POINT

The default minimum code point allowed: .

private Set<CharacterPredicate>
inclusivePredicates

Filters for code points.

private int
maximumCodePoint

The maximum code point allowed.

private int
minimumCodePoint

The minimum code point allowed.

private IntUnaryOperator
random

The source of randomness.

Constructor Summary

AccessConstructor and Description
public
Builder()

Creates a new instance.

Method Summary

Modifier and TypeMethod and Description
public RandomStringGenerator

Returns:

A new RandomStringGenerator
build
()

Implements org.apache.commons.text.Builder.build.

Deprecated Use get().

Builds a new RandomStringGenerator.

public RandomStringGenerator.Builder

Returns:

this instance.
filteredBy
(final CharacterPredicate...
the predicates, may be null or empty.
predicates
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Limits the characters in the generated string to those that match at least one of the predicates supplied.

public RandomStringGenerator

Returns:

A new RandomStringGenerator.
get
()

Implements java.util.function.Supplier.get.

Builds a new RandomStringGenerator.

private void
public RandomStringGenerator.Builder

Returns:

this instance.
selectFrom
(final char...
set of predefined Characters for random string generation the Character can be, may be null or empty.
chars
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Limits the characters in the generated string to those who match at supplied list of Character.

public RandomStringGenerator.Builder

Returns:

this instance.
setAccumulate
(final boolean
whether calls accumulates the source of provided characters. The default is false.
accumulate
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Sets whether calls accumulates the source of provided characters.

public RandomStringGenerator.Builder

Returns:

this instance.
usingRandom
(final IntUnaryOperator
the source of randomness, may be null.
random
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Overrides the default source of randomness.

public RandomStringGenerator.Builder

Returns:

this instance.
usingRandom
(final TextRandomProvider
the source of randomness, may be null.
random
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Overrides the default source of randomness.

public RandomStringGenerator.Builder

Returns:

this instance.
withinRange
(final char[]...
array of characters array, expected is to pass min, max pairs through this arg.
pairs
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Sets the array of minimum and maximum char allowed in the generated string.

public RandomStringGenerator.Builder

Returns:

this instance.
withinRange
(final int
the smallest code point allowed (inclusive).
minimumCodePoint
,
final int
the largest code point allowed (inclusive).
maximumCodePoint
)
References Deprecated RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

Sets the minimum and maximum code points allowed in the generated string.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

accumulateback to summary
private boolean accumulate

Whether calls accumulates the source of provided characters. The default is false.

characterSetback to summary
private Set<Character> characterSet

The source of provided characters.

DEFAULT_LENGTHback to summary
public static final int DEFAULT_LENGTH

The default string length produced by this builder: .

DEFAULT_MAXIMUM_CODE_POINTback to summary
public static final int DEFAULT_MAXIMUM_CODE_POINT

The default maximum code point allowed: Character#MAX_CODE_POINT ().

DEFAULT_MINIMUM_CODE_POINTback to summary
public static final int DEFAULT_MINIMUM_CODE_POINT

The default minimum code point allowed: .

inclusivePredicatesback to summary
private Set<CharacterPredicate> inclusivePredicates

Filters for code points.

maximumCodePointback to summary
private int maximumCodePoint

The maximum code point allowed.

minimumCodePointback to summary
private int minimumCodePoint

The minimum code point allowed.

randomback to summary
private IntUnaryOperator random

The source of randomness.

Constructor Detail

Builderback to summary
public Builder()

Creates a new instance.

Method Detail

buildback to summary
public RandomStringGenerator build()

Implements org.apache.commons.text.Builder.build.

Deprecated

Use get().

Builds a new RandomStringGenerator.

Returns:RandomStringGenerator

A new RandomStringGenerator

Annotations
@Deprecated
@Override
filteredByback to summary
public RandomStringGenerator.Builder filteredBy(final CharacterPredicate... predicates)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Limits the characters in the generated string to those that match at least one of the predicates supplied.

Passing null or an empty array to this method will revert to the default behavior of allowing any character. Multiple calls to this method will replace the previously stored predicates.

Parameters
predicates:CharacterPredicate[]

the predicates, may be null or empty.

Returns:RandomStringGenerator.Builder

this instance.

getback to summary
public RandomStringGenerator get()

Implements java.util.function.Supplier.get.

Builds a new RandomStringGenerator.

Returns:RandomStringGenerator

A new RandomStringGenerator.

Annotations
@Override
Since
1.12.0
initCharListback to summary
private void initCharList()
selectFromback to summary
public RandomStringGenerator.Builder selectFrom(final char... chars)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Limits the characters in the generated string to those who match at supplied list of Character.

Passing null or an empty array to this method will revert to the default behavior of allowing any character. Multiple calls to this method will replace the previously stored Character.

Parameters
chars:char[]

set of predefined Characters for random string generation the Character can be, may be null or empty.

Returns:RandomStringGenerator.Builder

this instance.

Since
1.2
setAccumulateback to summary
public RandomStringGenerator.Builder setAccumulate(final boolean accumulate)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Sets whether calls accumulates the source of provided characters. The default is false.

RandomStringGenerator gen = RandomStringGenerator.builder()
        .setAccumulate(true)
        .withinRange(new char[][] { { 'a', 'z' }, { 'A', 'Z' }, { '0', '9' } })
        .selectFrom('!', '"', '#', '$', '&', '\'', '(', ')', ',', '.', ':', ';', '?', '@', '[',
                    '\\', ']', '^', '_', '`', '{', '|', '}', '~') // punctuation
        // additional builder calls as needed
        .build();

Parameters
accumulate:boolean

whether calls accumulates the source of provided characters. The default is false.

Returns:RandomStringGenerator.Builder

this instance.

Since
1.14.0
usingRandomback to summary
public RandomStringGenerator.Builder usingRandom(final IntUnaryOperator random)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Overrides the default source of randomness. It is highly recommended that a random number generator library like Apache Commons RNG be used to provide the random number generation.

TextRandomProvider is a functional interface and need not be explicitly implemented:

UniformRandomProvider rng = RandomSource.create(...);
    RandomStringGenerator gen = RandomStringGenerator.builder()
        .usingRandom(rng::nextInt)
        // additional builder calls as needed
        .build();

Passing null to this method will revert to the default source of randomness.

Parameters
random:IntUnaryOperator

the source of randomness, may be null.

Returns:RandomStringGenerator.Builder

this instance.

Since
1.14.0
usingRandomback to summary
public RandomStringGenerator.Builder usingRandom(final TextRandomProvider random)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Overrides the default source of randomness. It is highly recommended that a random number generator library like Apache Commons RNG be used to provide the random number generation.

TextRandomProvider is a functional interface and need not be explicitly implemented:

UniformRandomProvider rng = RandomSource.create(...);
    RandomStringGenerator gen = RandomStringGenerator.builder()
        .usingRandom(rng::nextInt)
        // additional builder calls as needed
        .build();

Passing null to this method will revert to the default source of randomness.

Parameters
random:TextRandomProvider

the source of randomness, may be null.

Returns:RandomStringGenerator.Builder

this instance.

withinRangeback to summary
public RandomStringGenerator.Builder withinRange(final char[]... pairs)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Sets the array of minimum and maximum char allowed in the generated string. For example:

char[][] pairs = { { '0', '9' } };
char[][] pairs = { { 'a', 'z' } };
char[][] pairs = { { 'a', 'z' }, { '0', '9' } };

Parameters
pairs:char[][]

array of characters array, expected is to pass min, max pairs through this arg.

Returns:RandomStringGenerator.Builder

this instance.

withinRangeback to summary
public RandomStringGenerator.Builder withinRange(final int minimumCodePoint, final int maximumCodePoint)

References Deprecated

RandomStringGenerator.Builder is deprecated or references (maybe indirectly) at least one deprecated element.

See corresponding docs for further information.

Sets the minimum and maximum code points allowed in the generated string.

Parameters
minimumCodePoint:int

the smallest code point allowed (inclusive).

maximumCodePoint:int

the largest code point allowed (inclusive).

Returns:RandomStringGenerator.Builder

this instance.

Exceptions
IllegalArgumentException: