如何从 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.
推荐答案两种主要方式.
使用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).
如果您想知道是否有 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(ComparatorparingInt(o -> System.identityHashCode(o) ^ random)).findFirst().get();最好使用 Collections#shuffle() 代替.
更多推荐
从 List<E> 中取出 n 个随机元素?
发布评论