Languages
[Edit]
EN

Java - get random element from set

4 points
Created by:
Root-ssh
177980

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.
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - collections

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join