Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java program to generate a unique and random six alpha numeric code

I need to generate a reservation code of 6 alpha numeric characters, that is random and unique in java.

Tried using UUID.randomuuid().toString(), However the id is too long and the requirement demands that it should only be 6 characters.

What approaches are possible to achieve this?

Just to clarify, (Since this question is getting marked as duplicate). The other solutions I've found are simply generating random characters, which is not enough in this case. I need to reasonably ensure that a random code is not generated again.

like image 911
Mishal Harish Avatar asked Jan 27 '26 08:01

Mishal Harish


1 Answers

Consider using the hashids library to generate salted hashes of integers (your database ids or other random integers which is probably better).

http://hashids.org/java/

Hashids hashids = new Hashids("this is my salt",6);
String id = hashids.encode(1, 2, 3);
long[] numbers = hashids.decode(id);
like image 76
Strelok Avatar answered Jan 28 '26 23:01

Strelok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!