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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
rust
use axum::{ async_trait, extract::{rejection::JsonRejection, FromRequest, Request}, http::StatusCode,
A validated JSON extractor in Axum
extractors
validation
error-handling
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.