Java random string generation

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?).

Источник

Creating a random string with A-Z and 0-9 in Java [duplicate]

As the title suggest I need to create a random, 17 characters long, ID. Something like " AJB53JHS232ERO0H1 ". The order of letters and numbers is also random. I thought of creating an array with letters A-Z and a 'check' variable that randoms to 1-2 . And in a loop;

Randomize 'check' to 1-2. If (check == 1) then the character is a letter. Pick a random index from the letters array. else Pick a random number. 

you can put your letters and digits into an array and then randomly choose elements from it until you reach your desired size.

4 Answers 4

Here you can use my method for generating Random String

protected String getSaltString() < String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder salt = new StringBuilder(); Random rnd = new Random(); while (salt.length() < 18) < // length of the random string. int index = (int) (rnd.nextFloat() * SALTCHARS.length()); salt.append(SALTCHARS.charAt(index)); >String saltStr = salt.toString(); return saltStr; > 

The above method from my bag using to generate a salt string for login purpose.

Or just create a char[] given that you know exactly how long it will be. No need to append anything. I'd also use Random.nextInt rather than calling nextFloat and multiplying it by the length.

One thing to keep in mind if you use this is that, the Random class is sudo random and not a true random. Tried to use this to print 400 Strings to a file and found that it wasn't as random as I wanted. 🙁

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase() 

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

You can also use RandomStringUtils.random(length, useLetters, useNumbers) where length is int while useLetters and useNumbers are boolean values.

@NeriaNachum where are you seeing that RandomStringUtils has been replaced/deprecated? I'm just seeing "RandomStringUtils is intended for simple use cases. For more advanced use cases consider using Apache Commons Text's RandomStringGenerator instead." here

Using RandomStringGenerator (from apachae common) you can produce a random String of desired length. Following snippet will generate a String of length between 5 - 15 ( both inclusive) // char [][] pairs = <,,>; RandomStringGenerator randomStringGenerator = new RandomStringGenerator.Builder() .withinRange(pairs) .build(); String randomString = randomStringGenerator.generate(5, 15); //

Three steps to implement your function:

Step#1 You can specify a string, including the chars A-Z and 0-9.

 String candidateChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 

Step#2 Then if you would like to generate a random char from this candidate string. You can use

 candidateChars.charAt(random.nextInt(candidateChars.length())); 

Step#3 At last, specify the length of random string to be generated (in your description, it is 17). Writer a for-loop and append the random chars generated in step#2 to StringBuilder object.

Based on this, here is an example public class RandomTest

public static void main(String[] args) < System.out.println(generateRandomChars( "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 17)); >/** * * @param candidateChars * the candidate chars * @param length * the number of random chars to be generated * * @return */ public static String generateRandomChars(String candidateChars, int length) < StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) < sb.append(candidateChars.charAt(random.nextInt(candidateChars .length()))); >return sb.toString(); > > 

Источник

How can I generate random strings in java? [duplicate]

Here are the examples to generate two types of strings.

import java.security.SecureRandom; import java.math.BigInteger; public final class SessionIdentifierGenerator < private SecureRandom random = new SecureRandom(); public String nextSessionId() < return new BigInteger(130, random).toString(32); >> 

OUTPUT: ponhbh78cqjahls5flbdf4dlu4

String uuid = UUID.randomUUID().toString(); System.out.println("uuid http://download.oracle.com/javase/1,5.0/docs/api/java/util/UUID.html" rel="nofollow">here

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Nov 14, 2011 at 5:46
1
    1
    here is my answer . your posts was very useful . thanks a lot public class RandomeString < public char randomNumber() < int randomNum = 97 + (new Random()).nextInt(122-97); char randomChar = (char)randomNum; return randomChar; >public String RandomS(int n) < StringBuilder sb = new StringBuilder(); for(int i=0 ; iString s = sb.toString(); return s; >
    – Rojin
    Nov 15, 2011 at 6:31
Add a comment|
2

Well, you first write a function that will give you a random character meeting your requirements, then wrap that up in a for loop based on the desired length.

The following program gives one way of doing this, using a constant pool of characters and a random number generator:

import java.util.Random; public class testprog < private static final char[] pool = < 'a','b','c','d','e','f','g', 'h','i','j','k','l','m','n', 'o','p','q','r','s','t','u', 'v','w','x','y','z'>; private Random rnd; public testprog () < rnd = new Random(); >public char getChar() < return pool[rnd.nextInt(pool.length)]; >public String getStr(int sz) < StringBuilder sb = new StringBuilder(); for (int i = 0; i < sz; i++) sb.append(getChar()); return new String(sb); >public static void main(String[] args) < testprog tp = new testprog (); for (int i = 0; i < 10; i++) System.out.println (tp.getStr(i+5)); >>

On one particular run, that gives me:

hgtbf xismun cfdnazi cmpczbal vhhxwjzbx gfjxgihqhh yjgiwnftcnv ognwcvjucdnm hxiyqjyfkqenq jwmncfsrynuwed 

Now, you can adjust the pool of characters if you want it from a different character set, you can even adjust the skewing towards specific characters by changing how often they occur in the array (more e characters than z , for example).

But that should be a good start for what you're trying to do.

Источник

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.

Источник

Читайте также:  Python точка входа main
Оцените статью