how to reduce length of UUID generated using randomUUID( )

If you don't need it to be unique, you can use any length you like.

For example, you can do this.

Random rand = new Random();
char[] chars = new char[16];
for(int i=0;i<chars.length;i++) {
    chars[i] = (char) rand.nextInt(65536);
    if (!Character.isValidCodePoint(chars[i]))
        i--;
}
String s = new String(chars);

This will give you almost the same degree of randomness but will use every possible character between \u0000 and \ufffd

If you need printable ASCII characters you can make it as short as you like but the likelihood of uniqueness drops significantly. What can do is use base 36 instead of base 16

UUID uuid = UUID.randomUUID();
String s = Long.toString(uuid.getMostSignificantBits(), 36) + '-' + Long.toString(uuid.getLeastSignificantBits(), 36);

This will 26 characters on average, at most 27 character.

You can use base64 encoding and reduce it to 22 characters.

If you use base94 you can get it does to 20 characters.

If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes.

If you don't care about Strings you can use 16, 8-bit bytes.


String uuid = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));

String uuid16digits = uuid.substring(uuid.length() - 16);

This will return the last 16 digits of actual uuid.

Tags:

Java

Uuid