- How to generate a random String in Java [duplicate]
- Generate Random String in Java using Apache Commons Text
- Setup Apache Commons Text in Java project
- How to use org.apache.commons.text.RandomStringGenerator
- Generate random String with digits, letters and special characters
- Generate random String with digits and letters
- Generate random String with digits only
- Generate random String with letters only
- Generate random String with lowercase letters only
- Generate random String with capital letters only
- Generate random String with with limit list of characters
- How to generate random string with no duplicates in java
- 3 Answers 3
How to generate a random String in Java [duplicate]
I have an object called Student , and it has studentName , studentId , studentAddress , etc. For the studentId , I have to generate random string consist of seven numeric charaters, eg.
studentId = getRandomId(); studentId = "1234567"
If I read your question correctly, you want to generate a random number R such that 1,000,000
These 3 single line codes are very much useful i guess.. Long.toHexString(Double.doubleToLongBits(Math.random())); UUID.randomUUID().toString(); RandomStringUtils.randomAlphanumeric(16);
how can you ensure uniqueness given limited dimension of data? If number of students exceeds 10^7, you'll have no way to assign a unique number to each.
7 Answers 7
Generating a random string of characters is easy - just use java.util.Random and a string containing all the characters you want to be available, e.g.
public static String generateString(Random rng, String characters, int length) < char[] text = new char[length]; for (int i = 0; i < length; i++) < text[i] = characters.charAt(rng.nextInt(characters.length())); >return new String(text); >
Now, for uniqueness you'll need to store the generated strings somewhere. How you do that will really depend on the rest of your application.
@chandra: Yes, exactly. Give it a string of the characters you want to select from. So if you only wanted digits you'd pass in "0123456789". If you wanted only capital letters you'd pass in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" etc.
@Is7aq: Well it provides considerably more control over the output, both in terms of which characters are used and how long the string is.
@RockOnGom: Sorry, I'd missed this comment before. For things like this, I view the Random as effectively a dependency - accepting it here allows the caller to decide whether to use a preseeded Random to get repeatable results (e.g. for tests), a SecureRandom to make it suitable for security purposes, etc.
There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.
You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.
Random UUIDs are basically guaranteed to be unique though. If you need numeric string from that then hash it.
Random ran = new Random(); int top = 3; char data = ' '; String dat = ""; for (int i=0; i System.out.println(dat);
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator < private static final SetgeneratedNumbers = new HashSet(); public RandomNumberGenerator() < >public static void main(String[] args) < final int maxLength = 7; final int maxTry = 10; for (int i = 0; i < 10; i++) < System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry)); >> public static String getRandomId(final int maxLength, final int maxTry) < final Random random = new Random(System.nanoTime()); final int max = (int) Math.pow(10, maxLength); final int maxMin = (int) Math.pow(10, maxLength-1); int i = 0; boolean unique = false; int randomId = -1; while (i < maxTry) < randomId = random.nextInt(max - maxMin - 1) + maxMin; synchronized (generatedNumbers) < if (generatedNumbers.contains(randomId) == false) < unique = true; break; >> i++; > if (unique == false) < throw new RuntimeException("Cannot generate unique id!"); >synchronized (generatedNumbers) < generatedNumbers.add(String.valueOf(randomId)); >return String.valueOf(randomId); > >
The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.
Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable or HashMap containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).
Generate Random String in Java using Apache Commons Text
In this article we show how to generate random String values in Java using the RandomStringGenerator class of Apache Commons Text library. We provide multiple Java code examples with different settings to generate different kinds of data that may be useful for your daily programming scenarios.
Setup Apache Commons Text in Java project
If you are using Gradle build then add the following dependency configuration into build.gradle file.
compile group: 'org.apache.commons', name: 'commons-text', version: '1.9'
Or add the following dependency XML tag to pom.xml file if you are using Maven build.
org.apache.commons commons-text 1.9
Or download commons-text-1.9.jar file from Apache Commons Text download page at commons.apache.org
How to use org.apache.commons.text.RandomStringGenerator
In order to generate a String you need to create an object of RandomStringGenerator class by Builder class and provide settings for output random String. Then invoke the generate() method which provides the length of output random string to generate new random String.
Generate random String with digits, letters and special characters
import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample1 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .withinRange('0', 'z') .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
D2LVJ Oev@X@CVUk =JEMbq4zAGAy5aT
Generate random String with digits and letters
import org.apache.commons.text.CharacterPredicates; import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample2 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .withinRange('0', 'z') .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS) .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
FkB4D p4Bq9TmoTP HKllI0k1xzLZnlf
Generate random String with digits only
import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample3 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .withinRange('0', '9') .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
95697 6933738894 203250212308008
Generate random String with letters only
import org.apache.commons.text.CharacterPredicates; import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample4 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .withinRange('A', 'z') .filteredBy(CharacterPredicates.LETTERS) .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
CIHqA FSJWnVJQMY IjKJPRiowylevae
Generate random String with lowercase letters only
import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample5 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .withinRange('a', 'z') .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
yadkz ixbzammknr ynmngbxboevkrxz
Generate random String with capital letters only
import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample6 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .withinRange('A', 'Z') .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
MTPDB WKGLVJZMEV MGFPUTINWJBNTIO
Generate random String with with limit list of characters
import org.apache.commons.text.RandomStringGenerator; public class RandomStringGeneratorExample7 public static void main(String[] args) RandomStringGenerator generator = new RandomStringGenerator .Builder() .selectFrom("12345-".toCharArray()) .build(); String generatedString1 = generator.generate(5); String generatedString2 = generator.generate(10); String generatedString3 = generator.generate(15); System.out.println(generatedString1); System.out.println(generatedString2); System.out.println(generatedString3); > >
3--33 51--252-21 2-51-1515141555
How to generate random string with no duplicates in java
I read some answers , usually they use a set or some other data structure to ensure there is no duplicates. but for my situation , I already stored a lot random string in database , I have to make sure that the generated random string should not existed in database . and I don't think retrieve all random string from database into a set and then generated the random string is a good idea. I found that System.currentTimeMillis() will generate a "random" number , but how to translate that number to a random string is a question. I need a string with length 8. any suggestion will be appreciated
sure you can append 7 digit random number to some letter to make it 8 digit random string.And System.currentTimeMillis does not generate random number. it just gives you current time in millis from January 1, 1970 UTC
First of all, currentTimeMillis isn't even remotely random. I think your premise is basically flawed, but you only need to generate a random string and check for existence against the DB, which is a lot more light weight than reading the DB into a set. Have a look at UUID's - they might work for you.
You don't need to retrieve all the strings from DB, use UNIQUE constraint on your random strings column. It will fail inserting any duplicate string this way.
3 Answers 3
You can use Apache library for this: RandomStringUtils
RandomStringUtils.randomAlphanumeric(8).toUpperCase() // for alphanumeric RandomStringUtils.randomAlphabetic(8).toUpperCase() // for pure alphabets
randomAlphabetic(int count) Creates a random string whose length is the number of characters specified.
randomAlphanumeric(int count) Creates a random string whose length is the number of characters specified.
So there are two issues here - creating the random string, and making sure there's no duplicate already in the db.
If you are not bound to 8 characters, you can use a UUID as the commenter above suggested. The UUID class returns a strong that is highly statistically unlikely to be a duplicate of a previously generated UUID so you can use it for this precise purpose without checking if its already in your database.
Or if you don't care whether what the unique id is as long as its unique you could use an identity or autoincrement field which pretty much all DB's support. If you do that, though you have the read the record after you commit it to get the identity assigned by the db.
which produces a string which looks something that looks like this:
5e0013fd-3ed4-41b4-b05d-0cdf4324bb19
If you are have to have an 8 character string as your unique id and you don't want to import the apache library, \you can generate random 8 character string like this:
final String alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; final Random rand= new Random(); public String myUID() < int i = 8; String uid=""; while (i-- >0) < uid+=alpha.charAt(rand.nextInt(26)); >return uid; >
To make sure its not a duplicate, you should add a unique index to the column in the db which contains it. You can either query the db first to make sure that no row has that id before you insert the row, or catch the exception and retry if you've generated a duplicate.