Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

Java - get random element from set

0 contributions
4 points

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.
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more