Apache Commons has a method to generate random string
RandomStringUtils.randomAlphanumeric(10)
Does guava hava a similar method?
Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .
Using Java 8 StreamYou can also generate a random alphanumeric string of fixed length using streams in Java. A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters.
To generate random characters, we should use the rand() method. It generates integer values at random. This number is created using an algorithm associated with the specific time it is called and returns a succession of seemingly unrelated numbers.
It all depends on your needs, for some cases you can use the following:
private final Random random = new Random(); // or SecureRandom
String generate() {
final byte[] buffer = new byte[5];
random.nextBytes(buffer);
return BaseEncoding.base64Url().omitPadding().encode(buffer); // or base32()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With