Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does guava have a method to generate random strings?

Tags:

java

random

guava

Apache Commons has a method to generate random string

RandomStringUtils.randomAlphanumeric(10)

Does guava hava a similar method?

like image 938
wangxl Avatar asked Dec 26 '13 10:12

wangxl


People also ask

How do you create a random string?

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 .

Can we generate random 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.

How do you generate a random string in CPP?

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.


1 Answers

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()
}
like image 110
Alex Panchenko Avatar answered Oct 22 '22 09:10

Alex Panchenko