Java:检索 ArrayList 的随机不连续子列表(最有效的方法)

标签 java random arraylist set sublist

简而言之,我的问题是: 检索具有给定大小的 ArrayList 的随机不连续子列表的最有效方法是什么。

以下是我自己的设计,它有效但对我来说似乎有点笨拙。顺便说一句,这是我的第一个 JAVA 程序,所以如果我的代码或问题不符合最佳实践,请原谅 ;)

备注:
- 我的列表不包含重复项
- 我猜测如果 AimSize 超过原始列表大小的一半,则删除项目而不是添加项目可能会更快

public ArrayList<Vokabel> subList(int AimSize) {
    ArrayList<Vokabel> tempL = new ArrayList<Vokabel>();
    Random r = new Random();
    LinkedHashSet<Vokabel> tempS = new LinkedHashSet<Vokabel>();

    tempL = originalList;

    // If the size is to big just leave the list and change size 
    // (in the real code there is no pass-by-value problem ;)
    if (!(tempL.size() > AimSize)) {
        AimSize = tempL.size();
    // set to avoid duplicates and get a random order
    } else if (2* AimSize < tempL.size()) {
        while (tempS.size() < AimSize) {
            tempS.add(tempL.get(r.nextInt(tempL.size())));
        }
        tempL = new ArrayList<Vokabel>(tempS);
    // little optimization if it involves less loops
    // to delete entries to get to the right size, than to add them
    // the List->Set->List conversion at the end is there to reorder the items
    } else {
        while (tempL.size() > AimSize) {
            tempL.remove(r.nextInt(tempL.size()));
        }
        tempL = new ArrayList<Vokabel>(new LinkedHashSet<Vokabel>(tempL));

    }

    return tempL;
}

最佳答案

警告:这是在我的浏览器中编码的。它甚至可能无法编译!

使用 Collections.shuffleList.subList将完成这项工作。

public static <T> List<T> randomSubList(List<T> list, int newSize) {
    list = new ArrayList<>(list);
    Collections.shuffle(list);
    return list.subList(0, newSize);
}

关于Java:检索 ArrayList 的随机不连续子列表(最有效的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28582726/

相关文章:

c++ - 使用线程生成唯一随机数

python - 验证均匀分布的 3D 坐标的分布

java - 循环通过 JSONObject 创建数组 Java

java - 使用动态生成的类进行 Hazelcast 用户代码部署

java - EJB3.0 将句柄序列化为 Stateful Bean

python - 如何预测 Python 随机数生成器的输出?

java - 指向新引用的 ArrayList 会调用 GC

java - 在 Java 中实现 ArrayList 并获取各个值

java - 如何在java字节码中引用 "this"对象

java - Thymeleaf "foreach"无根元素