将大型ArrayList拆分为块并异步迭代

时间:2018-03-05 19:32:20

标签: java android performance

是否有任何有效的方法来迭代大ArrayList(100k大小)

for(Set set : sets) {
   //complex logic
}

有没有办法将ArrayList拆分成多个较小的ArrayList并将它们迭代到自己的线程中?

编辑: 它在Android中,我无法在API 16中使用流

1 个答案:

答案 0 :(得分:0)

以编程方式,在Android中应该可以将大型列表拆分为多个子列表,并将该线程分配给异步执行任务。以下是Java中的代码,我认为Android将是类似的东西:

import java.util.ArrayList;
import java.util.List;

public class SplitArrayList {

public SplitArrayList() {
}

public void split(List<Integer> list) {
    int start = 0;
    while (start < list.size() - 1) {
        assignTask(list.subList(start, start + 10000));
        start += 10000;
    }
}

public void assignTask(List<Integer> subList) {
    new TaskThread(subList).start();
}

public static void main(String[] args) {
    SplitArrayList obj = new SplitArrayList();
    List<Integer> list = new ArrayList<>();
    for (int i = 0; i < 100000; i++) {
        list.add(new Integer(i));
    }
    obj.split(list);
    }
}

class TaskThread extends Thread {

private List<Integer> subList;

public TaskThread(List<Integer> subList) {
    this.subList = subList;
}

@Override
public void run() {
    System.out.println("Starting from " + this.subList.get(0) + " and ending on "
            + this.subList.get(this.subList.size() - 1) + " with size " + this.subList.size());
}
}