有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java循环数组列表的批处理

我想在小批量中迭代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;
}

共 (3) 个答案

  1. # 1 楼答案

    您需要的是:Lists.partition(java.util.List, int)来自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. # 2 楼答案

    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);
            }
    
  3. # 3 楼答案

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

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