Java:随机生成不同的名称

发布于 2024-10-18 02:42:56 字数 79 浏览 0 评论 0原文

我需要用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

白色秋天 2024-10-25 02:42:56

我很晚才回答这个问题,但这对新读者来说真正有用。
这是获取随机有效名称的一种非常简单且有效的方法。
为此,请在 POM.xml 中添加 Maven 存储库

<dependency>
    <groupId>com.github.javafaker</groupId>
    <artifactId>javafaker</artifactId>
    <version>0.12</version>
</dependency>

,然后在 Java 代码中使用如下所示的 Faker 类

Faker faker = new Faker();

String name = faker.name().fullName();
String firstName = faker.name().firstName();
String lastName = faker.name().lastName();

String streetAddress = faker.address().streetAddress();

尝试使用标准 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

<dependency>
    <groupId>com.github.javafaker</groupId>
    <artifactId>javafaker</artifactId>
    <version>0.12</version>
</dependency>

And then use the Faker class as below in your Java code

Faker faker = new Faker();

String name = faker.name().fullName();
String firstName = faker.name().firstName();
String lastName = faker.name().lastName();

String streetAddress = faker.address().streetAddress();

Try printing the result using standard System.out.println();

For more reference Faker Lib

谎言 2024-10-25 02:42:56
// class variable
final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890";

final java.util.Random rand = new java.util.Random();

// consider using a Map<String,Boolean> to say whether the identifier is being used or not 
final Set<String> identifiers = new HashSet<String>();

public String randomIdentifier() {
    StringBuilder builder = new StringBuilder();
    while(builder.toString().length() == 0) {
        int length = rand.nextInt(5)+5;
        for(int i = 0; i < length; i++) {
            builder.append(lexicon.charAt(rand.nextInt(lexicon.length())));
        }
        if(identifiers.contains(builder.toString())) {
            builder = new StringBuilder();
        }
    }
    return builder.toString();
}
// class variable
final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890";

final java.util.Random rand = new java.util.Random();

// consider using a Map<String,Boolean> to say whether the identifier is being used or not 
final Set<String> identifiers = new HashSet<String>();

public String randomIdentifier() {
    StringBuilder builder = new StringBuilder();
    while(builder.toString().length() == 0) {
        int length = rand.nextInt(5)+5;
        for(int i = 0; i < length; i++) {
            builder.append(lexicon.charAt(rand.nextInt(lexicon.length())));
        }
        if(identifiers.contains(builder.toString())) {
            builder = new StringBuilder();
        }
    }
    return builder.toString();
}
还不是爱你 2024-10-25 02:42:56

为什么不使用 java.util.UUID ?
它保证生成唯一标识符,并且它是标准的:-)。

例如

String random = UUID.randomUUID().toString();

,或者甚至

int desiredLength = 5;
String random = UUID.randomUUID()
                    .toString()
                    .substring(0, desiredLength);

会产生 desiredLength 的一些随机 String,例如:

6e9c3

Why not use java.util.UUID?
It is guaranteed to generate unique identifiers, and it is as standard as it gets :-).

e.g.

String random = UUID.randomUUID().toString();

Or even

int desiredLength = 5;
String random = UUID.randomUUID()
                    .toString()
                    .substring(0, desiredLength);

Which will result in some random String of desiredLength, like:

6e9c3
指尖微凉心微凉 2024-10-25 02:42:56

如果您允许 Apache Commons 语言...

public String[] getRandomlyNames(final int characterLength, final int generateSize) {
    HashSet<String> list = new HashSet<String>();
    for (int i = 0; i < generateSize; ++i) {
        String name = null;
        do {
            name = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(
                    org.apache.commons.lang.math.RandomUtils.nextInt(characterLength - 1) + 1);
        while(list.contains(name));
        list.add(name);
    }
    return list.toArray(new String[]{});
}

If you permit Apache Commons lang...

public String[] getRandomlyNames(final int characterLength, final int generateSize) {
    HashSet<String> list = new HashSet<String>();
    for (int i = 0; i < generateSize; ++i) {
        String name = null;
        do {
            name = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(
                    org.apache.commons.lang.math.RandomUtils.nextInt(characterLength - 1) + 1);
        while(list.contains(name));
        list.add(name);
    }
    return list.toArray(new String[]{});
}
趴在窗边数星星i 2024-10-25 02:42:56

我遇到了同样的问题,但我需要一个任意长的字符串。我想出了这一行,无需外部库,将为您提供 10 个字符:

BigInteger.probablePrime(50, new Random()).toString(Character.MAX_RADIX)

长度可以更改,每个字符大约需要 5 位。所做的就是过滤并限制长度,如下所示(仅小写字母,大小为 10):

BigInteger.probablePrime(100, new Random()).
    toString(Character.MAX_RADIX).
    replaceAll("[0-9]", "").
    substring(0, 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:

BigInteger.probablePrime(50, new Random()).toString(Character.MAX_RADIX)

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):

BigInteger.probablePrime(100, new Random()).
    toString(Character.MAX_RADIX).
    replaceAll("[0-9]", "").
    substring(0, 10) 

Disadvantage: it's a bit slow.

遇见了你 2024-10-25 02:42:56

您可以尝试获取当前时间的 md5 哈希值,您将获得数字和字母混合的“随机”标识符

You can try to take md5 hash of current time and you will get "random" identifier as mixture of numbers and letters

不爱素颜 2024-10-25 02:42:56

最简单、最快的方法是生成某个字符串的排列。只要字符串足够长,您就可以轻松拥有 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..

静水深流 2024-10-25 02:42:56

你可以尝试

Random rand = new Random();
Set<String> words = new HashSet<String>();
while(words.size() < 10000) 
    words.add(Long.toString(Math.abs(rand.nextLong() % 3656158440062976L), 36)));

long 常量对于 10 位、36 基数的数字来说就足够了。

You could try

Random rand = new Random();
Set<String> words = new HashSet<String>();
while(words.size() < 10000) 
    words.add(Long.toString(Math.abs(rand.nextLong() % 3656158440062976L), 36)));

The long constant is just enough for 10 digit, base 36 numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文