Java:随机生成不同的名称
我需要用 Java 生成 10,000 个唯一标识符。标识符应由数字和字母组成,每个字符少于 10 个。有什么想法吗?内置库将是一个额外的优势。
I need to generate 10,000 unique identifiers in Java. The identifiers should be a mixture of numbers and letters and less than 10 characters each. Any ideas? Built in libraries would be an extra plus.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我很晚才回答这个问题,但这对新读者来说真正有用。
这是获取随机有效名称的一种非常简单且有效的方法。
为此,请在 POM.xml 中添加 Maven 存储库
,然后在 Java 代码中使用如下所示的 Faker 类
尝试使用标准
System.out.println();
打印结果有关更多参考 Faker Lib
I am answering this very late, but this is what really useful for new reader.
This is a very simple and efficient way to get random VALID names.
To do so, add maven repository in POM.xml
And then use the Faker class as below in your Java code
Try printing the result using standard
System.out.println();
For more reference Faker Lib
为什么不使用 java.util.UUID ?
它保证生成唯一标识符,并且它是标准的:-)。
例如
,或者甚至
会产生
desiredLength
的一些随机String
,例如:Why not use
java.util.UUID
?It is guaranteed to generate unique identifiers, and it is as standard as it gets :-).
e.g.
Or even
Which will result in some random
String
ofdesiredLength
, like:如果您允许 Apache Commons 语言...
If you permit Apache Commons lang...
我遇到了同样的问题,但我需要一个任意长的字符串。我想出了这一行,无需外部库,将为您提供 10 个字符:
长度可以更改,每个字符大约需要 5 位。所做的就是过滤并限制长度,如下所示(仅小写字母,大小为 10):
缺点:有点慢。
I had the same problem, but I needed an arbitrarily long string. I came up with this one-liner, no external library needed, that will give you 10 characters:
The length can be changed, you need about 5 bits per character. What did is filter and limit the length as follows (just lowercase letters, and size 10):
Disadvantage: it's a bit slow.
您可以尝试获取当前时间的 md5 哈希值,您将获得数字和字母混合的“随机”标识符
You can try to take md5 hash of current time and you will get "random" identifier as mixture of numbers and letters
最简单、最快的方法是生成某个字符串的排列。只要字符串足够长,您就可以轻松拥有 10,000 种独特的排列。生成排列的好处是您不必担心重复。如果一个字符串包含所有不同的字符,它可以生成n!排列(n 是字符串的长度)。因此,具有 8 个不同字符的字符串可以生成 40,320 种不同的排列。
在线有许多代码可以生成字符串的排列,例如这个 http ://introcs.cs.princeton.edu/23recursion/Permutations.java.html。
如果你想让它们更加随机,你可以使用不同的字符串作为种子,例如“abcde123”,“efgh456”等。
The easiest and fastest way is to generate permutations of a certain string. As long as the string is long enough, you can easily have 10,000 unique permutations. The good thing of generating permutation is that you don't have to worry about duplications. If a string contains all different characters, it can generate n! permutations (n is the length of the string). So a string with 8 different characters can generate 40,320 different permutations.
There are many code on-line to generate permutations of a string, such as this one http://introcs.cs.princeton.edu/23recursion/Permutations.java.html.
If you want them to be more random, you can use different strings as the seed, such as "abcde123", "efgh456", etc..
你可以尝试
long 常量对于 10 位、36 基数的数字来说就足够了。
You could try
The long constant is just enough for 10 digit, base 36 numbers.