Anand03 Anand03 - 6 months ago 55
Java Question

Loop arraylist in batches

I want to loop an arraylist in small batch sizes. For example: If the arrraylist size is 75 and the batch size is 10, I want to write a loop in such a way that it processes 0 to 10 records, 10 to 20 records, 20 - 30 records and so on. I tried something like 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;

}


Can someone please help?

Regards

Answer

see 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 reminder = 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(reminder!=0){

     end = end - batchSize + reminder;
  for(int counter = start ; counter < end ; counter ++)
                    {
                    //access array as a[counter]

                    }
    }