RandomStringGenerator for generating alphanumeric strings

Can I use the Apache generic text RandomStringGenerator to generate random alphanumeric strings (numbers and lowercase or uppercase letters)?

+5
source share
3 answers

Yes, using the following code:

 import static org.apache.commons.text.CharacterPredicates.DIGITS; import static org.apache.commons.text.CharacterPredicates.LETTERS; // ... RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange('0', 'z') .filteredBy(LETTERS, DIGITS) .build(); 
+23
source

I use this:

 static char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'z', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'y', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Z', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Y', 'X', 'C', 'V', 'B', 'N', 'M' }; private static String randomString(int length) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < length; i++) { stringBuilder.append(chars[new Random().nextInt(chars.length)]); } return stringBuilder.toString(); } 

or

 private static String randomString(int length) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < length; i++) { switch (new Random().nextInt(3)) { case 0: stringBuilder.append((char) (new Random().nextInt(9) + 48)); break; case 1: stringBuilder.append((char) (new Random().nextInt(25) + 65)); break; case 2: stringBuilder.append((char) (new Random().nextInt(25) + 97)); break; default: break; } } return stringBuilder.toString(); } enter code here 
+3
source

With Java 8 Expressions:

  private final RandomStringGenerator generator = new RandomStringGenerator.Builder() .usingRandom(max -> RandomUtils.getRandomAlphanumericChar()).build(); .................... public class RandomUtils { private final static char[] ALPHA_NUMERIC_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private final static Random random = new SecureRandom(); public static char getRandomAlphanumericChar() { return ALPHA_NUMERIC_CHARS[random.nextInt(ALPHA_NUMERIC_CHARS.length)]; } } 
-1
source

Source: https://habr.com/ru/post/1269559/


All Articles