Java\'s UUID class generates a random UUID. But this consists of letters and numbers. For some applications we need only numbers. Is there a way to generate random UUID that
Why don't just generate Random number and put it into format you want?
This won't give you uniqueness out of the box. (i.e. You will have to implement check on each generation and retry logic)
Where as other solutions which are taking UUID bits and converting them to number will be more granular in uniqueness. depending on your usecase you might still want to check uniqueness with this approach.
UUID uuid = UUID.randomUUID();
String numericUUID = Long.toString(uuid.getMostSignificantBits())
+ Long.toString(uuid.getLeastSignificantBits());
Random
is not universally unique. If you want to use UUIDs
as opposed to the Random class as suggested by others, you could simply use a regex to strip out everything except numerics from the UUID. Try something like this,
String id = UUID.randomUUID().toString().replaceAll("[^0-9]", "");
The simpliest way:
uuid.uuid4().int
For the record: UUIDs are in fact 128 bit numbers.
What you see as an alphanumeric string is the representation of that 128 bit number using hexadecimal digits (0..9A..F).
The real solution is to transform the string into it's correspondent 128 bit number. And to store that you'll need two Longs (Long has 64 bit).
If you dont want a random number, but an UUID with numbers only use:
String lUUID = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
in this case left padded to 40 zeros...
results for:
UUID : b55081fa-9cd1-48c2-95d4-efe2db322a54
in:
UUID : 0241008287272164729465721528295504357972