Java Set Draw Example
In Java, when dealing with collections, it’s often useful to retrieve a random element – draw – from a Set. Java provides the java.util.Random class and, ThreadLocalRandom class in the java.util.concurrent. In this article, we’ll explore different methods to get a random element from a Java Set.
1. The Set Interface in Java
A Set is a collection of elements without duplicates. The Set interface is part of the Java collections library and is implemented by classes such as HashSet, LinkedHashSet, and TreeSet. A Set is suitable for scenarios where you need to store and manage unique values.
2. Getting a Random Element Using the Random Class
To get a random element from a Set in Java, we can use the java.util.Random class to generate random numbers and then use that to retrieve a random element from the Set. Below is an example:
public class RandomElementFromSet {
public static void main(String[] args) {
// Create a HashSet
Set<String> fruits = new HashSet<>();
fruits.add("orange");
fruits.add("banana");
fruits.add("apple");
fruits.add("guava");
fruits.add("pineapple");
// Get a random element from the set
String randomFruit = getRandomElement(fruits);
// Print the random element
System.out.println("Random Fruit: " + randomFruit);
}
private static <T> T getRandomElement(Set<T> set) {
if (set.isEmpty()) {
return null;
}
// Convert the set to an array
T[] array = (T[]) set.toArray();
// Use Random to get a random index
Random random = new Random();
int randomIndex = random.nextInt(array.length);
// Return the random element
return array[randomIndex];
}
}
In this example, we first create a HashSet and then provide a helper method named getRandomElement that takes a Set as an argument. This method first checks if the set is not empty, converts it to an array, and then generates a random index within the range of the set size. Finally, it returns the element at the randomly selected index of the array.
Now, if we run the main class, the result should be a random output as shown below:
3. Getting a Random Element Using the ThreadLocalRandom Class
This method is similar to the previous ones but employs the ThreadLocalRandom class to obtain a random index. The ThreadLocalRandom class provides a more efficient and thread-safe alternative to Random.
The code listing below shows how to get a random element from a Set using the ThreadLocalRandom class.
public class RandomSetElementThreadLocal {
public static void main(String[] args) {
// Create a Set (e.g., HashSet)
Set<String> fruits = new HashSet<>();
fruits.add("orange");
fruits.add("banana");
fruits.add("apple");
fruits.add("guava");
fruits.add("pineapple");
// Use ThreadLocalRandom to get a random element
int randomIndex = ThreadLocalRandom.current().nextInt(fruits.size());
// Use an iterator to get the element at the random index
String randomFruit = getRandomElement(fruits, randomIndex);
// Print the random element
System.out.println("Random Fruit: " + randomFruit);
}
// Helper method to get the element at a specific index in a Set
private static <T> T getRandomElement(Set<T> set, int index) {
int currentIndex = 0;
for (T element : set) {
if (currentIndex == index) {
return element;
}
currentIndex++;
}
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + set.size());
}
}
In this example:
- First, we create a
Setand in this example, we use aHashSet. - Next, we use the
ThreadLocalRandom.current().nextInt(size)method to generate a random index within the size of the set. This index will be used to access a random element later. - Next, we created a helper method
getRandomElement(Set<T> set, int index)which is used to iterate through the set and retrieve the element at the specified index. - And, Finally, in our
mainclass, we use the helper method to retrieve the random element with:String randomElement = getRandomElement(stringSet, randomIndex);.
4. Conclusion
In this article, we explored how to leverage the Random and ThreadLocalRandom classes in Java to retrieve a random element from a Set. We can choose between the traditional Random class and the more modern and thread-safe ThreadLocalRandom class, providing us with solutions for integrating randomness into our applications.
5. Download the Source Code
This was an example of how to retrieve a random element from a draw Set sample in Java.
You can download the full source code of this example here: Retrieve a Random Element from a Draw Set Sample in Java


