【问题标题】:Loop arraylist in batches [duplicate]批量循环arraylist [重复]
【发布时间】:2014-05-28 19:38:41
【问题描述】:

我想以小批量迭代 ArrayList。

例如,如果 ArrayList 大小为 75,batch 大小为 10,我希望它处理记录 0-10,然后是 10-20,然后是 20-30,等等。

我试过了,但是没用:

int batchSize = 10;
int start = 0;
int end = batchSize;

for(int counter = start ; counter < end ; counter ++)
{
    if (start > list.size())
    {
        System.out.println("breaking");
        break;
    }

    System.out.println("counter   " + counter);
    start = start + batchSize;
    end = end + batchSize;
}

【问题讨论】:

  • 在什么情况下不起作用?
  • 计数器变量没有正确的值。输出为:计数器 0 计数器 1 计数器 2 计数器 3 计数器 4 计数器 5 计数器 6 断开
  • 这与您期望看到的有何不同?我们无法读懂您的想法,也不知道您在list 中拥有什么数据。
  • 我创建的arraylist包含随机数量的String元素[总共63个元素]。第一次迭代中的计数器值为 0,这是正确的。但我假设在随后的迭代中值应该是 10、20 等。

标签: java for-loop arraylist batch-processing


【解决方案1】:

你需要的是:Lists.partition(java.util.List, int) from Google Guava

例子:

final List<String> listToBatch = new ArrayList<>();
final List<List<String>> batch = Lists.partition(listToBatch, 10);
for (List<String> list : batch) {
  // Add your code here
}

【讨论】:

  • 非常舒适,应该是恕我直言的首选解决方案,尤其是当数据已经以列表形式存在时。
【解决方案2】:

您可以像批量大小和列表大小的余数一样查找计数。

int batchSize = 10;
int start = 0;
int end = batchSize;

int count = list.size() / batchSize;
int remainder = list.size() % batchSize;
int counter = 0;
for(int i = 0 ; i < count ; i ++)
{
    System.out.println("counter   " + counter);
    for(int counter = start ; counter < end ; counter ++)
    {
        //access array as a[counter]
    }
    start = start + batchSize;
    end = end + batchSize;
}

if(remainder != 0)
{
    end = end - batchSize + remainder;
    for(int counter = start ; counter < end ; counter ++)
    {
       //access array as a[counter]
    }
}

【讨论】:

  • 感谢输入,我看到上面的输出如下: counter 0 counter 1 counter 2 counter 3 counter 4 counter 5..... 但是,我想修改逻辑是这样的这样我就可以在每次迭代中处理 10 个一组的数组列表索引。对于第一次迭代,计数器从 0 开始,对于下一次迭代,计数器从 10 开始,依此类推
  • 使用编辑过的答案
  • 再次感谢。上述逻辑有效,我可以正确看到计数器变量。您能否帮助修改上述逻辑,使:1)每次迭代中处理的元素数量等于批量大小。 2)我可以使用for循环计数器变量'i'在每次迭代中访问相应的arraylist元素[意思是:第一次是0到9,第二次是10到19,依此类推]。
  • 我已经对您的要求进行了代码修改...内循环负责批量读取列表..外循环负责批处理需要运行的迭代次数..有任何疑问可以问我...如果满意,请投票并接受答案..
  • 再次感谢您的帮助。一个小小的疑问。我们可以修改上面的逻辑来摆脱外循环吗?如果我们可以设置一些条件,例如: if (counter > list.size()) {break;} 或任何其他适当的逻辑。
【解决方案3】:
int start = 0;
int end=updateBatchSize;
List finalList = null;
 try {
        while(end < sampleList.size()){
            if(end==sampleList.size()){
                break;
            }
            finalList = sampleList.subList(Math.max(0,start),Math.min(sampleList.size(),end));
            start=Math.max(0,start+updateBatchSize);
            end=Math.min(sampleList.size(),end+updateBatchSize);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2016-06-07
    • 2020-08-12
    相关资源
    最近更新 更多