Java 批量循环数组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23920425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:03:03  来源:igfitidea点击:

Loop arraylist in batches

javafor-looparraylistbatch-processing

提问by Anand03

I want to iterate through an ArrayList in small batch sizes.

我想以小批量迭代 ArrayList。

For example, if the ArrayList size is 75 and the batch size is 10, I want it to process records 0-10, then 10-20, then 20-30, etc.

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

I tried this, but it did not work:

我试过这个,但没有用:

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;
}

采纳答案by Karibasappa G C

You do it like remainder from batch size and list size to find count.

您可以像从批量大小和列表大小中取余一样来查找计数。

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]
    }
}

回答by Ash

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);
        }

回答by Tanmay Baid

What you need is: Lists.partition(java.util.List, int)from Google Guava

您需要的是:来自Google Guava 的Lists.partition(java.util.List, int)

Example:

例子:

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