就拿从列表&LT n个随机元素; E&GT;? [英] Take n random elements from a List<E>?
问题描述
我如何可以从n个随机元素的的ArrayList&LT; E&GT;
?理想情况下,我希望能够到取()
方法来获得另一个X的元素,无需更换。
How can I take n random elements from an ArrayList<E>
? Ideally, I'd like to be able to make successive calls to the take()
method to get another x elements, without replacement.
推荐答案
两种主要方式。
-
使用<一个href="http://download.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt%28int%29"><$c$c>Random#nextInt(int)$c$c>:
List<Foo> list = createItSomehow();
Random random = new Random();
Foo foo = list.get(random.nextInt(list.size()));
它不过不能保证连续 N
要求回报的独特元素。
It's however not guaranteed that successive n
calls returns unique elements.
使用<一个href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List%29"><$c$c>Collections#shuffle()$c$c>:
List<Foo> list = createItSomehow();
Collections.shuffle(list);
Foo foo = list.get(0);
它使您能够获得 N
一个递增的索引(假设列表本身含有独特的元素)。独特的元素
It enables you to get n
unique elements by an incremented index (assuming that the list itself contains unique elements).
这篇关于就拿从列表&LT n个随机元素; E&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!