Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)
I would like an efficient utility to generate unique sequences of bytes. UUID is a good candidate but UUID.randomUUID().toString()
generates stuff like 44e128a5-ac7a-4c9a-be4c-224b6bf81b20
which is good, but I would prefer dash-less string.
I'm looking for an efficient way to generate a random strings, only from alphanumeric characters (no dashes or any other special symbols).
Solution 1:
This does it:
public static void main(String[] args) {
final String uuid = UUID.randomUUID().toString().replace("-", "");
System.out.println("uuid = " + uuid);
}
Solution 2:
Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.
Solution 3:
I used JUG (Java UUID Generator) to generate unique ID. It is unique across JVMs. Pretty good to use. Here is the code for your reference:
private static final SecureRandom secureRandom = new SecureRandom();
private static final UUIDGenerator generator = UUIDGenerator.getInstance();
public synchronized static String generateUniqueId() {
UUID uuid = generator.generateRandomBasedUUID(secureRandom);
return uuid.toString().replaceAll("-", "").toUpperCase();
}
You could download the library from: https://github.com/cowtowncoder/java-uuid-generator