我如何可以从n个随机元素的的ArrayList< E>
?理想情况下,我希望能够到取()
方法来获得另一个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.
两种主要方式。
使用Random#nextInt(int):
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.
使用Collections#shuffle():
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).
上一篇:最长递增子最长