password method tutorial java code example

Example: java password

public static String generateRandomPassword(int length) {
        Object[][] characterSets = {
                {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'},
                {'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'}
        };
        List<Character> passwordCharacters = new ArrayList<>();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (Object[] characters : characterSets){
            for (int i = 0; i < length / 3; i++){
                passwordCharacters.add((Character) characters[random.nextInt(0, characters.length)]);
            }
        }
        for (int i =0; i < length % 3; i++){
            Object[] characters = characterSets[random.nextInt(0, characterSets.length)];
            passwordCharacters.add((Character) characters[random.nextInt(0, characters.length)]);
        }
        Collections.shuffle(passwordCharacters);
        StringBuilder stringBuilder = new StringBuilder(length);
        passwordCharacters.forEach(stringBuilder::append);
        return stringBuilder.toString();
    }

Tags:

Java Example