Random unique alpha numeric string in java

Viewed 339

I want to generate a string mix of numbers-capital and small characters but they should be unique with a specific length Is there any algorithm or library in java to generate unique strings?

2 Answers

Apache common lang utils is a great library for creating random numbers and many more useful stuff.

You can create a random string with letters and numbers as follows.

1 Get the dependency. In gradle it is -

compile group: 'org.apache.commons', name: 'commons-lang3'

2 import randomutils

import org.apache.commons.lang3.RandomStringUtils;

3 Generate random string of size 8 with letters = true and numbers = true

RandomStringUtils.random(8, true, true)
public class Main {
    public static void main(String[] args) {
        char[] array = "1234567890qwertyuiopasdfghjklzxcvbnm".toCharArray();
        String randomString = null;
        for (int x = 0; x < 10; x++;) {
            randomString += "" + array[0 + (int)(Math.random() * ((10 - 0) + 1))];
        }
    System.out.println("Your string is: " + randomString);
    }
}

This should work.

Related