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

标签 java algorithm random sampling

如何从 ArrayList<E> 中获取 n 个随机元素?理想情况下,我希望能够连续调用 take()方法来获取另一个 x 元素,无需替换。

最佳答案

两种主要方式。

  1. 使用Random#nextInt(int) :

    List<Foo> list = createItSomehow();
    Random random = new Random();
    Foo foo = list.get(random.nextInt(list.size()));
    

    但不能保证连续 n 调用返回唯一元素。

  2. 使用Collections#shuffle() :

    List<Foo> list = createItSomehow();
    Collections.shuffle(list);
    Foo foo = list.get(0);
    

    它使您能够通过递增的索引获取 n 个唯一元素(假设列表本身包含唯一元素)。


如果您想知道是否有 Java 8 Stream 方法;不,没有内置的。标准 API 中没有像 Comparator#randomOrder() 这样的东西(还没有?)。您可以尝试以下类似的方法,同时仍然满足严格的 Comparator 契约(Contract)(尽管分布非常糟糕):

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()

关于java - 从 List<E> 中取 n 个随机元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4702036/

相关文章:

algorithm - 使用全局变量将递归转换为使用堆栈的迭代

algorithm - 使用循环对数据进行分组(MATLAB 中的信号处理)

algorithm - Perl 中的快速排序

random - 如何在恒定时间内生成无偏随机 bigint

java - Android 8.0 Oreo 上不显示通知

java - 从文本文件读取的音乐播放器会同时播放所有片段 Javafx

Java Swing ; JFrame 弹出窗口

c - C中的偏置随机数生成器函数

boost - 将 boost 随机数生成器与 OpenMP 结合使用

java - fragment 错误android