首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一次从数组10中提取项的最佳方法

一次从数组10中提取项的最佳方法
EN

Stack Overflow用户
提问于 2016-02-10 06:01:11
回答 3查看 133关注 0票数 7

我有一个ArrayList,它可以包含无限数量的对象。我需要一次拉10个项目,并对它们进行操作。

我能想象的是这样做。

代码语言:javascript
复制
int batchAmount = 10;
for (int i = 0; i < fullList.size(); i += batchAmount) {
    List<List<object>> batchList = new ArrayList();
    batchList.add(fullList.subList(i, Math.min(i + batchAmount, fullList.size()));
    // Here I can do another for loop in batchList and do operations on each item
}

有什么想法吗?谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-02-10 06:23:06

你可以这样做:

代码语言:javascript
复制
int batchSize = 10;
ArrayList<Integer> batch = new ArrayList<Integer>();
for (int i = 0; i < fullList.size();i++) {
    batch.add(fullList.get(i));
    if (batch.size() % batchSize == 0 || i == (fullList.size()-1)) {
        //ToDo Process the batch;
        batch = new ArrayList<Integer>();
    }
}

当前实现的问题是在每次迭代时都要创建一个batchList,需要在循环之外声明这个列表(batchList)。类似于:

代码语言:javascript
复制
int batchAmount = 10;
List<List<object>> batchList = new ArrayList();
for (int i = 0; i < fullList.size(); i += batchAmount) {
    ArrayList batch = new ArrayList(fullList.subList(i, Math.min(i + batchAmount, fullList.size()));
    batchList.add(batch);
 }
 // at this point, batchList will contain a list of batches
票数 3
EN

Stack Overflow用户

发布于 2016-02-10 06:20:01

Guava library是由Google提供的,它方便了不同的功能。

代码语言:javascript
复制
List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);
List<Integer> countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}

List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}

来自https://stackoverflow.com/a/9534034/3027124https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists的答案

希望这能有所帮助。

票数 1
EN

Stack Overflow用户

发布于 2016-02-10 06:09:47

从ArrayList:ArrayList.remove(0)中提取元素

代码语言:javascript
复制
// clone the list first if you need the values in the future:
ArrayList<object> cloned = new ArrayList<>(list);
while(!list.isEmpty()){
    object[] tmp = new object[10];
    try{
        for(int i = 0; i < 10; i++) tmp[i] = list.remove(0);
    }catch(IndexOutOfBoundsException e){
        // end of list reached. for loop is auto broken. no need to do anything.
    }
    // do something with tmp, whose .length is <=10
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35307952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档