从 List<E> 中取出 n 个随机元素?

编程入门 行业动态 更新时间:2024-10-18 21:23:43
本文介绍了从 List<E> 中取出 n 个随机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从 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 个随机元素?

    本文发布于:2023-11-29 12:41:29,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1646424.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:元素   List   lt   gt

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!