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?
Asked
Active
Viewed 603 times
2
-
4Does this answer your question? [How to generate a random alpha-numeric string](https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string) – maloomeister Dec 08 '20 at 13:19
-
Generating a random string is straightforward, but guaranteeing uniqueness can be a problem. You could put the String's into a Set and check after each generated string. Then put the new unique string into the set. – NomadMaker Dec 08 '20 at 13:39
2 Answers
2
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)

midhun mathew
- 333
- 1
- 9
0
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.

Yhrrs
- 51
- 8
-
Note: I didn't have time to actually test it but you get the concept hopefully. – Yhrrs Dec 08 '20 at 14:02