从 List<E> 中取出 n 个随机元素? [英] Take n random elements from a List<E>?
问题描述
如何从 ArrayList
中取出 n 个随机元素?理想情况下,我希望能够连续调用 take()
方法以获取另一个 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.
推荐答案
两种主要方式.
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.
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).
<小时>
如果您想知道是否有 Java 8 Stream 方法;不,没有内置的.标准 API 中没有 Comparator#randomOrder()
之类的东西(还有吗?).您可以尝试以下类似操作,同时仍然满足严格的 Comparator
契约(尽管分布非常糟糕):
In case you're wondering if there's a Java 8 Stream approach; no, there isn't a built-in one. There's no such thing as Comparator#randomOrder()
in standard API (yet?). You could try something like below while still satisfying the strict Comparator
contract (although the distribution is pretty terrible):
List<Foo> list = createItSomehow();
int random = new Random().nextInt();
Foo foo = list.stream().sorted(Comparator.comparingInt(o -> System.identityHashCode(o) ^ random)).findFirst().get();
最好使用 Collections#shuffle()
代替.
这篇关于从 List<E> 中取出 n 个随机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!