Q:

Generate 5 random Strings and add them to a Set in Java

I am a beginner in Java and have the following issue.
How can I generate 5 random strings and add them to a Set?

A:

First, let's create the set:
Set<String> set = new HashSet<>();

Now, let's generate 5 random strings. There are many ways to do this, here is an answer about it. But since you did not ask for a specific length, let's proceed with this:
String randomStr = Long.toHexString(Double.doubleToLongBits(Math.random()));

Now, let's repeat the random generation 5 times:
for (int i = 0; i < 5; i++) {
    set.add(Long.toHexString(Double.doubleToLongBits(Math.random())));
}

Now, the problem is that this does not guarantee the set will have 5 random strings, as we may have similar ones. To ensure that, we should do:
while (set.size() < 5) {
    set.add(Long.toHexString(Double.doubleToLongBits(Math.random())));
}

The code above will continue generating random strings until the set contains at least 5. I'm not checking if it already contains the string because a Set, by definition, contains no duplicate elements. So, adding a duplicate won't increase the size.

A:

You can do something like
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        Random random = new Random();
        while (set.size() != 5) {
            set.add(String.valueOf((char) (65 + random.nextInt(26))));
        }
        System.out.println(set);
    }
}

A sample run:
[D, X, L, M, N]

Notes:

Random.nextInt(n) generates an int from 0 to n-1 where n is an int. Therefore,  65 + random.nextInt(26)) will generate a number from 65 to 90.
String.valueOf(c) converts c into a String where c is a char.
The ASCII value of A is 65 and that of Z is 90. So, ((char)65) will be printed as A.

