Test admin Test admin - 3 months ago 7
Java Question

How to generate 1000 unique email-ids using java

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.

Below is the code and output:

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;

}


and output is:

myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com
myqo@mail.com


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.

For Example:

myqo@mail.com
bfta@mail.com
kjuy@mail.com


etc...

I don't know how to loop it.

Any help is greatly appreciated. Thanks in advance.

Answer

Put your String initialization in the for statement:

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;
}

And it would be possible to call like:

generateEmail("gmail.com", 4);

As I understand, 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())