chunk

Returns a lazy iterable of lists, each holding up to size consecutive elements.

Iterable<List<A>> chunk<A>(int size, Iterable<A> iterable) FxAsyncIterable<List<A>> chunkAsync<A>(int size, FxAsyncIterable<A> iterable) Fx<List<T>> Fx.chunk(int size) // chain FxAsync<List<T>> FxAsync.chunk(int size)

Lecture

chunk batches a flat sequence into fixed-size groups — dealing cards into hands, paginating a result set, sending work to a downstream API in batches of n. It buffers just size elements at a time before yielding each list, so it stays lazy and memory-bounded even over a huge source; only the final chunk is allowed to come up short, if the source doesn't divide evenly.

The async version, chunkAsync, awaits size elements before producing each chunk — pair it with .concurrent(n) upstream to fill a chunk's worth of async work concurrently.

Demo 1 · Basics

10 items chunked by 3 leaves a shorter final chunk:

Demo 2 · Async

Try it yourself

Exercise: deal the cards into hands of 3.

Related: slice — a single arbitrary window instead of repeated batches · split — group by separator instead of fixed size · transpose — flip rows and columns of already-chunked data