Richard N
Richard N

Reputation: 925

Java: Efficient way to create arrays from arraylists in chunks

I am not a native JAVA programmer. I am creating a client for an web service API. The API basically requires an array argument.

I am parsing an XML file, creating records and then using this API to make a bulk INSERT.

The problem is that that this API can only insert 200 records at once that means my array can only have 200 records or less at the time of making the call.

Since I do not know how many records in advance, I store my records in an ArrayList and later convert it into an Array using .ToArray()

APIObject[] invoiceArray = invoiceObjectlist.toArray(new APIObject[invoiceDetailObjectlist.size()]);

Now because of the 200 limit problem posed by the API, I need to create these arrays in chunks of 200 till all records in the ArrayList have been inserted.

Right now am thinking that I can loop through the array list and maintain a counter. When the counter = 200, I can create a new array and insert all elements to that point by maintaining index pointers or I can push elements into a new array list for every 200 records and convert that into an array and perform the insert.

What would be a better elegant/efficient method to do this in JAVA?

Thanks.

Upvotes: 0

Views: 1773

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

List<APIObject[]> chunks = new ArrayList<APIObject[]>();
for (int i = 0; i < bigList.size(); i += 200) {
  APIObject[] chunk = bigList.subList(i, Math.min(bigList.size(), i + 200))
    .toArray(new APIObject[200]);
  chunks.add(chunk);
}

Upvotes: 6

Related Questions