Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Random selection of elements from a Set is a common requirement in various Java applications, especially in games and data processing tasks.

In this article, we’ll explore different methods to pick a random element from a Java Set.

2. Using the java.util.Random Class

The java.util.Random class is a handy tool for generating random numbers. To pick a random element from a Set, we can generate a random index and use it to access the element:

public static <T> T getByRandomClass(Set<T> set) {
    if (set == null || set.isEmpty()) {
        throw new IllegalArgumentException("The Set cannot be empty.");
    }
    int randomIndex = new Random().nextInt(set.size());
    int i = 0;
    for (T element : set) {
        if (i == randomIndex) {
            return element;
        }
        i++;
    }
    throw new IllegalStateException("Something went wrong while picking a random element.");
}

Let’s test our method:

Set<String> animals = new HashSet<>();
animals.add("Lion");
animals.add("Elephant");
animals.add("Giraffe");

String randomAnimal = getByRandomClass(animals);
System.out.println("Randomly picked animal: " + randomAnimal);

The result should be random:

Randomly picked animal: Giraffe

3. Using the ThreadLocalRandom Class

Starting from Java 7, the ThreadLocalRandom class provides a more efficient and thread-safe alternative for generating random numbers. Here’s how we can use it to pick a random index from a Set:

int randomIndex = ThreadLocalRandom.current().nextInt(set.size());

The solution is the same as above except for how the random number is selected.

Using ThreadLocalRandom is preferable over java.util.Random because it reduces contention in multi-threaded scenarios and generally offers better performance.

4. Conclusion

In summary, we’ve learned two ways to pick a random element from a Java Set.

The example code from this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.