Get a Random Element From a Set in Java – 用 Java 从集合中获取随机元素

最后修改: 2023年 8月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

Set 中随机选择元素是各种 Java 应用程序(尤其是游戏和数据处理任务)的常见要求。

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

在本文中,我们将探讨从 Java Set 中随机抽取元素的不同方法。

2. Using the java.util.Random Class

2.使用 java.util.Random

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:

java.util.Random 类是用于生成随机数的便捷工具。要从 Set 中选取一个随机元素,我们可以生成一个随机索引并使用它来访问该元素:

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

3.使用 ThreadLocalRandom

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:

从 Java 7 开始,ThreadLocalRandom 类为生成随机数提供了更高效、更线程安全的替代方法。以下是我们如何使用该类从 Set 中选取随机索引:</em

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.

java.util.Random 相比,使用 ThreadLocalRandom 更为可取,因为它可减少多线程场景中的争用,并通常提供更好的性能。

4. Conclusion

4.结论

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

总之,我们已经学会了从 Java Set 中随机抽取元素的两种方法。

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

本文的示例代码可在 GitHub 上找到