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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Ceiling division with (total + chunkSize - 1) / chunkSize sizes the result exactly without floating-point math.
- 2Math.min clamps the final chunk so the last batch never runs past the end of the source.
- 3Wrapping subList in a new ArrayList decouples chunks from the source, while returning the raw view keeps things lazy and cheap.
Related explainers
java
@Aspect @Component public class IdempotencyAspect {
How an idempotency aspect works in Spring
aop
idempotency
caching
Advanced
9 steps
java
package com.example.orders.messaging; import com.example.orders.dto.OrderEvent; import com.example.orders.service.OrderProcessingService;
Manual RabbitMQ acks in a Spring listener
message-queue
error-handling
acknowledgement
Intermediate
6 steps
java
package com.example.shop.repository; import com.example.shop.domain.Order; import com.example.shop.domain.OrderStatus;
Deriving JPA queries from method names in Spring
query derivation
repositories
pagination
Intermediate
8 steps
java
import java.util.List; import java.util.IntSummaryStatistics; public class OrderReport {
Aggregating stats with IntSummaryStatistics
streams
aggregation
records
Intermediate
5 steps
typescript
type StorageSchema = Record<string, unknown>; interface StorageOptions { namespace?: string;
A type-safe wrapper around localStorage
generics
type-safety
serialization
Intermediate
9 steps
java
public class OrderRepository { private static final int BATCH_SIZE = 500; private static final String INSERT_SQL =
Batched JDBC inserts with transaction safety
jdbc
batching
transactions
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/splitting-a-list-into-fixed-size-chunks-in-java-explained-java-a9bb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.