Java: Generating a random String (password, booking reference, etc)

If this is intended to be used as a password generator, make sure to use SecureRandom instead of Random in the examples below. You might also want to use char[] instead of String for storing the result.

Random string

int length = 8;
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             + "abcdefghijklmnopqrstuvwxyz"
             + "0123456789";
String str = new Random().ints(length, 0, chars.length())
                         .mapToObj(i -> "" + chars.charAt(i))
                         .collect(Collectors.joining());

With at least 1 digit and 1 special character

int length = 8;
String digits = "0123456789";
String specials = "~=+%^*/()[]{}/!@#$?|";
String all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
           + "abcdefghijklmnopqrstuvwxyz"
           + digits + specials;
Random rnd = new Random();
List<String> result = new ArrayList<>();
Consumer<String> appendChar = s ->
        result.add("" + s.charAt(rnd.nextInt(s.length())));
appendChar.accept(digits);
appendChar.accept(specials);
while (result.size() < length)
    appendChar.accept(all);
Collections.shuffle(result, rnd);
String str = String.join("", result);

See also

RandomStringUtils from Apache Commons Lang

Comments

Be the first to comment!