Batch Work With SubList Chunking
Split a list into fixed-size batches with subList windows so bulk calls respect API limits; each batch is a read-only view of the backing list.
Code
import java.util.ArrayList;
import java.util.List;
public class BatchSender {
// batches are views over the original list: the list stays unmodified during iteration and batch contents remain read-only
static <T> List<List<T>> chunk(List<T> source, int size) {
if (size <= 0) {
throw new IllegalArgumentException("size must be positive: " + size);
}
List<List<T>> batches = new ArrayList<>();
for (int i = 0; i < source.size(); i += size) {
batches.add(source.subList(i, Math.min(i + size, source.size())));
}
return batches;
}
public static void main(String[] args) {
List<Integer> ids = List.of(11, 22, 33, 44, 55, 66, 67);
// fixed-size slices: the tail batch shrinks automatically when fewer than size remain
for (List<Integer> batch : chunk(ids, 3)) {
System.out.println("send batch: " + batch);
}
// when size exceeds the total there is exactly one batch
System.out.println("one batch: " + chunk(ids, 100));
}
}What the code does
The working surface is the class BatchSender and the functions chunk and main — everything else is wiring.
for (int i = 0; i < source.size(); i += size) is the loop that carries the per-item work. Invalid states are rejected up front: it throws IllegalArgumentException instead of continuing with bad data.
Using it
The primary signature is static <T> List<List<T>> chunk(List<T> source, int size)
The demo output is labeled (send batch:, one batch:), so every printed line maps back to its originating operation.
Running the file executes main, which drives chunk in order.
Key statements
throw new IllegalArgumentException("size must be positive: " + size);
for (int i = 0; i < source.size(); i += size) {
batches.add(source.subList(i, Math.min(i + size, source.size())));
}
Interactive Tools for This Topic
FAQ
- What happens if the preconditions do not hold?
- The code refuses to continue: `IllegalArgumentException` is thrown while the state is still recoverable.
- What does Batch Work With SubList Chunking print when run?
- The script runs standalone; its 2 labeled outputs include `send batch:`, `one batch:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.