java 34 lines · 8 steps

Splitting a list into fixed-size chunks in Java

A utility class offers two ways to break a list into batches — eager copies and a lazy stream of views.

Explained by highlit
1public final class ListPartitioner {
2 
3 private ListPartitioner() {
4 }
5 
6 public static <T> List<List<T>> partition(List<T> source, int chunkSize) {
7 Objects.requireNonNull(source, "source must not be null");
8 if (chunkSize <= 0) {
9 throw new IllegalArgumentException("chunkSize must be positive: " + chunkSize);
10 }
11 
12 int total = source.size();
13 List<List<T>> chunks = new ArrayList<>((total + chunkSize - 1) / chunkSize);
14 
15 for (int start = 0; start < total; start += chunkSize) {
16 int end = Math.min(start + chunkSize, total);
17 chunks.add(new ArrayList<>(source.subList(start, end)));
18 }
19 
20 return chunks;
21 }
22 
23 public static <T> Stream<List<T>> partitionLazily(List<T> source, int chunkSize) {
24 if (chunkSize <= 0) {
25 throw new IllegalArgumentException("chunkSize must be positive: " + chunkSize);
26 }
27 
28 int total = source.size();
29 int batches = (total + chunkSize - 1) / chunkSize;
30 
31 return IntStream.range(0, batches)
32 .mapToObj(i -> source.subList(i * chunkSize, Math.min((i + 1) * chunkSize, total)));
33 }
34}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Ceiling division with (total + chunkSize - 1) / chunkSize sizes the result exactly without floating-point math.
  2. 2Math.min clamps the final chunk so the last batch never runs past the end of the source.
  3. 3Wrapping subList in a new ArrayList decouples chunks from the source, while returning the raw view keeps things lazy and cheap.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Splitting a list into fixed-size chunks in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code