就拿从列表&LT n个随机元素; E>? [英] Take n random elements from a List<E>?

查看:146
本文介绍了就拿从列表&LT n个随机元素; E>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以从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.

推荐答案

两种主要方式。

  1. 使用<一个href="http://download.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt%28int%29"><$c$c>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.

使用<一个href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List%29"><$c$c>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).

这篇关于就拿从列表&LT n个随机元素; E&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆