循环arraylist批量

Ana*_*d03 -2 java for-loop arraylist batch-processing

我想以小批量大小迭代ArrayList.

例如,如果ArrayList大小为75且批量大小为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;
}
Run Code Online (Sandbox Code Playgroud)

小智 9

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

例:

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


Kar*_*G C 5

您可以像批量大小和列表大小一样来查找余数.

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]
    }
}
Run Code Online (Sandbox Code Playgroud)