Languages
[Edit]
EN

Java - get random element from set

4 points
Created by:
Root-ssh
68980

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

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join