我想以小批量大小迭代一个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;
}
答案 0 :(得分:7)
您需要的是: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
}
答案 1 :(得分:6)
您可以像批量大小和列表大小那样使用余数来查找计数。
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]
}
}
答案 2 :(得分:0)
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);
}