问题描述
我的要求是用Java生成1000个唯一的电子邮件ID。我已经生成了随机文本并使用for循环我限制了要生成的电子邮件ID的数量。问题是,当我执行10个电子邮件时,会生成所有相同的电子邮件。
My requirement is to generate 1000 unique email-ids in Java. I have already generated random Text and using for loop I'm limiting the number of email-ids to be generated. Problem is when I execute 10 email-ids are generated but all are same.
以下是代码和输出:
public static void main() {
first fr = new first();
String n = fr.genText()+"@mail.com";
for (int i = 0; i<=9; i++) {
System.out.println(n);
}
}
public String genText() {
String randomText = "abcdefghijklmnopqrstuvwxyz";
int length = 4;
String temp = RandomStringUtils.random(length, randomText);
return temp;
}
输出为:
[email protected]
[email protected]
...
[email protected]
当我执行相同的上述程序时,我得到另一组mail-id。示例:而不是'myqo'
它将是'bfta'
。但我的要求是生成不同的唯一ID。
When I execute the same above program I get another set of mail-ids. Example: instead of 'myqo'
it will be 'bfta'
. But my requirement is to generate different unique ids.
例如:
[email protected]
[email protected]
[email protected]
推荐答案
在中为
语句添加字符串
初始化:
for (int i = 0; i<=9; i++) {
String n = fr.genText()+"@mail.com";
System.out.println(n);
}
我想稍微改写一下你的方法:
I would like to rewrite your method a little bit:
public String generateEmail(String domain, int length) {
return RandomStringUtils.random(length, "abcdefghijklmnopqrstuvwxyz") + "@" + domain;
}
可以这样打电话:
generateEmail("gmail.com", 4);
据我所知,你想生成独特的1000封电子邮件,然后你可以通过Stream API以方便的方式执行此操作:
As I understood, you want to generate unique 1000 emails, then you would be able to do this in a convenient way by Stream API:
Stream.generate(() -> generateEmail("gmail.com", 4))
.limit(1000)
.collect(Collectors.toSet())
但问题仍然存在。我故意将 Stream< String>
收集到 Set< String>
(删除重复项)以查找其尺寸()
。正如您所看到的,大小并不总是等于 1000
But the problem still exists. I purposely collected a Stream<String>
to a Set<String>
(which removes duplicates) to find out its size()
. As you may see, the size is not always equals 1000
999
1000
997
这意味着即使是这么小的算法,你的算法也会返回重复的值范围。
that means your algorithm returns duplicated values even for such small range.
因此,您最好研究已编写的Java电子邮件生成器或改进自己的(例如,通过添加数字,一些特殊字符,反过来,将生成)。
Therefore, you'd better research already written email generators for Java or improve your own (for example, by adding numbers, some special characters that, in turn, will generate a plenty of exceptions).
这篇关于如何使用java生成1000个唯一的电子邮件ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!