I want to generate a lot of random strings that unique of each other and unique in MySQL with specify the number of generated like 10,000.
I could make sure the strings are unique each other in every time generated strings, just check if the List[String]
contains the string in each time generate.
But I don't know how to make sure its unique in MySQL, I have been set the unique index in MySQL like ALTER TABLE Code ADD UNIQUE INDEX `codeUnique` (`code`);
But if the unique guarantee is when inserting data into MySQL, insert will failure.
And if check the insert failure in each time insert, generating will take a very very long time when the number of generated is large.
Use List.fill
and randomUUID
as @Sudhir notes:
scala> List.fill(10000)(java.util.UUID.randomUUID.toString)
res0: List[String] = List(
3c789851-975c-499d-8b0b-5bc60dee7497,
9511fb41-a42e-47d8-a5f3-ba1a6f3847f2,
61263421-59de-4538-87c6-eb98ccf1e19d,
...)
You can double check they are unique by converting it to a set and checking the size:
scala> List.fill(10000)(randomUUID.toString).toSet.size
res1: Int = 10000
You can simply use Java's java.util.UUID.randomUUID.toString
method to get unique String
. See doc here . Chances of getting duplicate keys using this method is very low (I never got duplicate keys). So you don't have to maintain a collection either.
If you want to use your own random key generator and want to make sure it's unique, you should not go for List[String]
because List
can have duplicates and for checking if a key already exists, you need to iterate over each elements, which is a costly operation. You should use Set[String]
instead and then use Set
's contains()
method to check if key is already present.
循环遍历10000个整数,取每个数字的MD5或SHA1。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.