How can I generate alphanumeric unique userId's of 5/6 digits reducing the chances of collision upto 10 lac values with Java? I don't want to make calls every time to the DB so as to check whether that ID already exists there.
Asked
Active
Viewed 1,050 times
0
-
If you want them to be persistent (i.e. survive after app restart) you need to use an external source or rely on something like SecureRandom. – khachik Jun 16 '18 at 13:37
-
another alternative (inspired by one of the answers below) is to use a unique information that is coming from users (like email) and hash it – khachik Jun 16 '18 at 13:38
-
I want to use these as userId's to login into an app. As per you the Secure Random thing will be suitable for me. If you can provide a link from where I can know more about this. – Siddharth Jun 16 '18 at 13:48
-
1You can have your database [generate it](https://learn.microsoft.com/en-us/sql/t-sql/data-types/uniqueidentifier-transact-sql?view=sql-server-2017). Alternatively see[UUID](https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html) – c0der Jun 16 '18 at 13:55
-
What is “lac values”? – Basil Bourque Jun 16 '18 at 22:28
-
5-6 digits or characters is not likely enough entropy to avoid collisions. If you want universally unique identifiers, use, well, [*Universally Unique Identifiers* (UUID)](https://en.wikipedia.org/wiki/Universally_unique_identifier). These are [128-bit values](https://en.wikipedia.org/wiki/128-bit). Some databases offer native support for such values. UUIDs are often displayed textually as a 36-character hex string with hyphens. – Basil Bourque Jun 16 '18 at 22:37
2 Answers
1
If your users do not supply any additional information (e.g. real name, email address, ...) you will have to try your luck with a purely random string as user name. One option to generate random strings is the RandomStringGenerator of Apache Commons Text.
import org.apache.commons.text.RandomStringGenerator;
...
RandomStringGenerator randomStringGenerator = new RandomStringGenerator.Builder()
.filteredBy(c -> Character.isLetterOrDigit(c) && c <= 122)
.build();
String username = RandomStringGenerator.generate(6)
This code will produce user names like
3gmNQJ
Hz4DXy
c6X99p
FZJ5jQ
twKgZG
7ukgAY
Lq9qgB
...
However, your actual logic should be prepared to handle collisions between user names. A 6 character long random string is not too safe not to generate any collisions on the long run.
A safer alternative are UUIDs, but they are much longer and not very user friendly if someone has to enter them during a login process.

werner
- 13,518
- 6
- 30
- 45
0
You can generate an hash code of the entire entity. Basing on the hashing algorithm you choose (e.g. SHA1) the collisions are very rare.

sirnino
- 437
- 3
- 13