Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What java library are there provides the the facility to generate unique random string combination from a given set of characters?

What java library are there provides the the facility to generate unique random string combination from a given set of characters?

Say I have these set of characters: [a-zA-Z0-9]

And I need to generate 4-character string from this set that is less likely to collide.

like image 224
quarks Avatar asked Dec 16 '22 07:12

quarks


2 Answers

Apache Commons Lang has a RandomStringUtils class with a method that takes a sequence of characters and a count, and does what you ask. It makes no guarantee of collision avoidance, though, and with only 4 characters, you're going to struggle to achieve that.

like image 170
skaffman Avatar answered Dec 28 '22 23:12

skaffman


And I need to generate 4-character string from this set that is less likely to collide.

Less likely than what? There are 62^4 = 14.8 million such strings. Due to the birthday paradox, you get about a 50% chance of a collision if you randomly generate 3800 of them. If that's not acceptable, no library will help you, you need to use a longer string or establish uniqueness explicitly (e.g. via incrementing an integer and formatting it in base 62).

like image 41
Michael Borgwardt Avatar answered Dec 29 '22 00:12

Michael Borgwardt