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_whenGeneratingRandomAlphanumericString_thenCorrect() {
3 int leftLimit = 48; // numeral '0'
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 .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
10 .limit(targetStringLength)
11 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
12 .toString();
13
14 System.out.println(generatedString);
15}
16