Quantcast
Channel: How to generate a random alpha-numeric string - Stack Overflow
Viewing all articles
Browse latest Browse all 47

Answer by Mayank for How to generate a random alpha-numeric string

$
0
0

I am using a very simple solution using Java 8. Just customize it according to your needs.

...import java.security.SecureRandom;...//Generate a random String of length between 10 to 20.//Length is also randomly generated here.SecureRandom random = new SecureRandom();String sampleSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";int stringLength = random.ints(1, 10, 21).mapToObj(x -> x).reduce((a, b) -> a).get();String randomString = random.ints(stringLength, 0, sampleSet.length() - 1)        .mapToObj(x -> sampleSet.charAt(x))        .collect(Collector            .of(StringBuilder::new, StringBuilder::append,                StringBuilder::append, StringBuilder::toString));

We can use this to generate an alphanumeric random String like this (the returned String will mandatorily have some non-numeric characters as well as some numeric characters):

public String generateRandomString() {    String sampleSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_";    String sampleSetNumeric = "0123456789";    String randomString = getRandomString(sampleSet, 10, 21);    String randomStringNumeric = getRandomString(sampleSetNumeric, 10, 21);    randomString = randomString + randomStringNumeric;    //Convert String to List<Character>    List<Character> list = randomString.chars()            .mapToObj(x -> (char)x)            .collect(Collectors.toList());    Collections.shuffle(list);    //This is needed to force a non-numeric character as the first String    //Skip this for() if you don't need this logic    for(;;) {        if(Character.isDigit(list.get(0))) Collections.shuffle(list);        else break;    }    //Convert List<Character> to String    randomString = list.stream()            .map(String::valueOf)            .collect(Collectors.joining());    return randomString;}//Generate a random number between the lower bound (inclusive) and upper bound (exclusive)private int getRandomLength(int min, int max) {    SecureRandom random = new SecureRandom();    return random.ints(1, min, max).mapToObj(x -> x).reduce((a, b) -> a).get();}//Generate a random String from the given sample string, having a random length between the lower bound (inclusive) and upper bound (exclusive)private String getRandomString(String sampleSet, int min, int max) {    SecureRandom random = new SecureRandom();    return random.ints(getRandomLength(min, max), 0, sampleSet.length() - 1)    .mapToObj(x -> sampleSet.charAt(x))    .collect(Collector        .of(StringBuilder::new, StringBuilder::append,            StringBuilder::append, StringBuilder::toString));}

Viewing all articles
Browse latest Browse all 47

Latest Images

Trending Articles





Latest Images