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

216

如何从一个集合中随机选取元素? 我特别希望能在Java中从HashSet或LinkedHashSet中随机选择一个元素。 其他语言的方案也可以考虑。


5
你应该指定一些条件来确定这是否是你真正想要的。
  • 你将选择多少次随机元素?
  • 数据需要存储在 HashSet 还是 LinkedHashSet 中?两者都不支持随机访问。
  • HashSet 很大吗?键很小吗?
- David Nehme
35个回答

0

你也可以将集合转换为数组,使用数组。在小规模上,这可能会起作用。我看到最受欢迎的答案中的for循环是O(n)。

Object[] arr = set.toArray();

int v = (int) arr[rnd.nextInt(arr.length)];

0

如果您不介意使用第三方库,Utils 库有一个 IterableUtils,其中包含一个 randomFrom(Iterable iterable) 方法,该方法将接受一个 Set 并返回其中的一个随机元素。

Set<Object> set = new HashSet<>();
set.add(...);
...
Object random = IterableUtils.randomFrom(set);

它在Maven中央仓库中:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>

0
List<Integer> list=new ArrayList<Integer>(set);
int r=(int)(Math.random()*set.size());
return list.get(r);

问题是关于Set的,即不是 java.util.List - undefined

-1
如果集合大小不大,那么可以使用数组来完成。
int random;
HashSet someSet;
<Type>[] randData;
random = new Random(System.currentTimeMillis).nextInt(someSet.size());
randData = someSet.toArray();
<Type> sResult = randData[random];

-3

阅读完这个帖子后,我能写出的最好的代码是:

static Random random = new Random(System.currentTimeMillis());
public static <T> T randomChoice(T[] choices)
{
    int index = random.nextInt(choices.length);
    return choices[index];
}

2
这个问题是关于集合而不是数组的。另外,没有必要用当前时间来初始化Randomnew Random()会返回一个已经正确初始化的实例。 - dimo414

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接