Is there anyway to split ArrayList into different parts without knowing size of it until runtime? I know there is a method called:
list.subList(a,b);
listSize = oldlist.size();
chunksize =1000;
chunks = list.size()/chunksize;
ArrayList subLists;
ArrayList finalList;
int count = -1;
for(int i=0;i<chunks;i++){
subLists = new ArrayList();
int j=0;
while(j<chunksize && count<listSize){
subList.add(oldList.get(++count))
j++;
}
finalList.add(subLists)
}
You can use this finalList as it contains the list of chuncks of the oldList.
If you're constrained by PL/SQL in
limits then you want to know how to split a list into chunks of size <=n, where n is the limit. This is a much simpler problem as it does not require knowing the size of the list in advance.
Pseudocode:
for (int n=0; n<list.size(); n+=limit)
{
chunkSize = min(list.size,n+limit);
chunk = list.sublist(n,chunkSize);
// do something with chunk
}
generic method for your help :
private static List<List<Object>> createBatch(List<Object> originalList,
int chunkSize) {
List<List<Object>> listOfChunks = new ArrayList<List<Object>>();
for (int i = 0; i < originalList.size() / chunkSize; i++) {
listOfChunks.add(originalList.subList(i * chunkSize, i * chunkSize
+ chunkSize));
}
if (originalList.size() % chunkSize != 0) {
listOfChunks.add(originalList.subList(originalList.size()
- originalList.size() % chunkSize, originalList.size()));
}
return listOfChunks;