1import java.util.Random;
2
3public class Generator {
4 public static String generateRandomPassword(int len) {
5 String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk"
6 +"lmnopqrstuvwxyz!@#$%&";
7 Random rnd = new Random();
8 StringBuilder sb = new StringBuilder(len);
9 for (int i = 0; i < len; i++)
10 sb.append(chars.charAt(rnd.nextInt(chars.length())));
11 return sb.toString();
12 }
13}
1@Test
2public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
3 int leftLimit = 97; // letter 'a'
4 int rightLimit = 122; // letter 'z'
5 int targetStringLength = 10;
6 Random random = new Random();
7
8 String generatedString = random.ints(leftLimit, rightLimit + 1)
9 .limit(targetStringLength)
10 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
11 .toString();
12
13 System.out.println(generatedString);
14}