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}
1public static String getRandomString(int size) {
2 // The string that we will return
3 String rand = "";
4 // The chars that are used to generate the random string
5 String chars = "1234567890-=!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\"zxcvbnm,./ZXCVBNM<>?";
6 // Loop based on the requested size
7 for (int i = 0; i < size; i++) {
8 // Add a random char from the chars string to the rand string
9 rand += chars.toCharArray()[new Random().nextInt(chars.length())];
10 }
11 // Return the random string
12 return rand;
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
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}