从集合中选择一个随机元素

2022-01-17 00:00:00 algorithm random set language-agnostic java

如何从集合中随机选择一个元素?我对从 a 中选择一个随机元素特别感兴趣Java 中的 HashSet 或 LinkedHashSet.也欢迎其他语言的解决方案.

How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome.

推荐答案

int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
    if (i == item)
        return obj;
    i++;
}

相关文章