Languages
[Edit]
EN

Java - get random element from set

4 points
Created by:
Root-ssh
6412

1. Convert HashSet to ArrayList via constructor

public static String randomStringFromSet() {
	Set<String> set = new HashSet<>(Arrays.asList("A", "B", "C", "D", "E", "F"));
	List<String> list = new ArrayList<>(set);

	int size = list.size();
	int randIdx = new Random().nextInt(size);

	String randomElem = list.get(randIdx);
	return randomElem;
}

Example:

System.out.println(randomStringFromSet()); // C
System.out.println(randomStringFromSet()); // D
System.out.println(randomStringFromSet()); // B

Not very efficient because we need to create ArrayList based on HashSet.
So if the set is not too large it's ok solution.

2. Iteration + random number

public static String randomStringFromSet2() {
	Set<String> set = new HashSet<>(Arrays.asList("A", "B", "C", "D", "E", "F"));
	int size = set.size();

	int currIdx = 0;
	int randIdx = new Random().nextInt(size);

	for (String letter : set) {
		if (currIdx == randIdx) {
			return letter;
		}
		currIdx++;
	}

	return null;
}

Example:

System.out.println(randomStringFromSet2()); // D
System.out.println(randomStringFromSet2()); // F
System.out.println(randomStringFromSet2()); // E
  • Iterate over the set and generate random number within size of the set.
  • Iterate over the elements of the set and keep index
  • If index is equal to the randomly generated index then return element from set.

Java - random numbers

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.