Class Chunking
All chunking methods preserve the encounter order of the input.
In particular, collectors such as chunkedBy(BiPredicate) and
weightedChunks(long, ToLongFunction) define their semantics
in terms of adjacent elements in the encounter order. Supplying an
unordered or non-deterministic stream may therefore produce
non-deterministic chunk boundaries.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumDefines how to handle the trailing remainder when the input size is not evenly divisible by the chunk size. -
Method Summary
Modifier and TypeMethodDescriptionchunk(int chunkSize, T... elements) Varargs convenience method: chunks an array of elements.Chunks anIterableinto a list of lists, using its iteration order.chunk(Collection<T> collection, int chunkSize) Chunks aCollectioninto a list of lists, using its iteration order.chunk(Spliterator<T> spliterator, int chunkSize) Chunks aSpliteratorinto a list of lists, using its traversal order.chunk(DoubleStream stream, int chunkSize) Chunks aDoubleStreamintoList<List<Double>>and closes it.Chunks anIntStreamintoList<List<Integer>>and closes it.chunk(LongStream stream, int chunkSize) Chunks aLongStreamintoList<List<Long>>and closes it.Chunks aStreaminto a list of lists and closes the stream.chunkedBy(BiPredicate<? super T, ? super T> sameGroup) Returns aCollectorthat groups elements into chunks based on a boundary predicate.static <T> voidforEachChunk(Stream<T> source, int chunkSize, Chunking.RemainderPolicy remainderPolicy, Consumer<? super List<T>> chunkHandler) Processes each fixed-size chunk from the given source stream using the provided consumer, with an explicitChunking.RemainderPolicy.static <T> voidforEachChunk(Stream<T> source, int chunkSize, Consumer<? super List<T>> chunkHandler) Processes each fixed-size chunk from the given source stream using the provided consumer, without materializing all chunks in memory at once.slidingWindows(int windowSize, int step) streamOfChunks(Stream<T> source, int chunkSize) Returns aStreamof fixed-size chunks from the given source stream.streamOfChunks(Stream<T> source, int chunkSize, Chunking.RemainderPolicy remainderPolicy) Returns aStreamof fixed-size chunks from the given source stream, using the givenChunking.RemainderPolicy.streamOfSlidingWindows(Stream<T> source, int windowSize) streamOfSlidingWindows(Stream<T> source, int windowSize, int step) Returns aStreamof sliding windows of sizewindowSizewith the given step.toChunks(int chunkSize) Returns aCollectorthat groups elements into chunks ofchunkSize, including the final partial chunk if any.toChunks(int chunkSize, Chunking.RemainderPolicy remainderPolicy) Returns aCollectorthat groups elements into chunks ofchunkSize, using the providedChunking.RemainderPolicy.toChunks(int chunkSize, Chunking.RemainderPolicy remainderPolicy, IntFunction<C> chunkFactory) Returns aCollectorthat groups elements into chunks ofchunkSize, using both a customChunking.RemainderPolicyand a custom chunk list implementation.static <T,C extends List<T>, OC extends Collection<C>>
Collector<T,?, OC> toChunks(int chunkSize, Chunking.RemainderPolicy remainderPolicy, IntFunction<C> chunkFactory, Supplier<OC> outerCollectionFactory) Returns aCollectorthat groups elements into chunks ofchunkSize, using a customChunking.RemainderPolicy, a custom chunk list implementation, and a custom outer collection type.toChunks(int chunkSize, IntFunction<C> chunkFactory) Returns aCollectorthat groups elements into chunks ofchunkSize, using a custom list implementation for each chunk.toDoubleChunks(int chunkSize) Convenience collector forDoubleStreams.toIntChunks(int chunkSize) Convenience collector forIntStreams.toLongChunks(int chunkSize) Convenience collector forLongStreams.weightedChunks(long maxWeight, ToLongFunction<? super T> weigher) Returns aCollectorthat groups elements into chunks such that the sum of weights (as provided byweigher) within each chunk is <=maxWeight.
-
Method Details
-
toChunks
Returns aCollectorthat groups elements into chunks ofchunkSize, including the final partial chunk if any.Works with any stream source (lists, sets, arrays via
Arrays.stream, etc.).- Type Parameters:
T- the element type of the stream- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a collector that accumulates elements into a
List<List<T>> - Throws:
IllegalArgumentException- ifchunkSizeis less than1
-
toChunks
public static <T> Collector<T,?, toChunksList<List<T>>> (int chunkSize, Chunking.RemainderPolicy remainderPolicy) Returns aCollectorthat groups elements into chunks ofchunkSize, using the providedChunking.RemainderPolicy.- Type Parameters:
T- the element type of the stream- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zeroremainderPolicy- how to handle the final partial chunk; must not benull- Returns:
- a collector that accumulates elements into a
List<List<T>> - Throws:
IllegalArgumentException- ifchunkSizeis less than1NullPointerException- ifremainderPolicyisnull
-
toChunks
public static <T,C extends List<T>> Collector<T,?, toChunksList<C>> (int chunkSize, IntFunction<C> chunkFactory) Returns aCollectorthat groups elements into chunks ofchunkSize, using a custom list implementation for each chunk.The
chunkFactoryis called once per chunk, with the intended size of that chunk (number of elements). Implementations may ignore the hint.The final partial chunk is included (equivalent to
Chunking.RemainderPolicy.INCLUDE_PARTIAL).- Type Parameters:
T- the element typeC- the list implementation used for chunks- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zerochunkFactory- factory used to create each chunk list; must not benull- Returns:
- a collector that accumulates elements into a
List<C> - Throws:
IllegalArgumentException- ifchunkSizeis less than1NullPointerException- ifchunkFactoryisnull
-
toChunks
public static <T,C extends List<T>> Collector<T,?, toChunksList<C>> (int chunkSize, Chunking.RemainderPolicy remainderPolicy, IntFunction<C> chunkFactory) Returns aCollectorthat groups elements into chunks ofchunkSize, using both a customChunking.RemainderPolicyand a custom chunk list implementation.- Type Parameters:
T- the element typeC- the list implementation used for chunks- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zeroremainderPolicy- how to handle the final partial chunk; must not benullchunkFactory- factory used to create each chunk list; must not benull- Returns:
- a collector that accumulates elements into a
List<C> - Throws:
IllegalArgumentException- ifchunkSizeis less than1NullPointerException- ifremainderPolicyorchunkFactoryisnull
-
toChunks
public static <T,C extends List<T>, Collector<T,OC extends Collection<C>> ?, toChunksOC> (int chunkSize, Chunking.RemainderPolicy remainderPolicy, IntFunction<C> chunkFactory, Supplier<OC> outerCollectionFactory) Returns aCollectorthat groups elements into chunks ofchunkSize, using a customChunking.RemainderPolicy, a custom chunk list implementation, and a custom outer collection type.This overload is useful when you want the outer collection to be something other than a
List, for example aLinkedHashSetof chunk lists.Collector<Integer, ?, LinkedHashSet<List<Integer>>> collector = Chunking.toChunks( 3, RemainderPolicy.INCLUDE_PARTIAL, ArrayList::new, LinkedHashSet::new );- Type Parameters:
T- the element typeC- the list implementation used for individual chunksOC- the outer collection type that will hold all chunks- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zeroremainderPolicy- how to handle the final partial chunk; must not benullchunkFactory- factory used to create each chunk list; must not benullouterCollectionFactory- factory used to create the outer collection; must not benull- Returns:
- a collector that accumulates elements into an
OC - Throws:
IllegalArgumentException- ifchunkSizeis less than1NullPointerException- ifremainderPolicy,chunkFactory, orouterCollectionFactoryisnull
-
streamOfChunks
Returns aStreamof fixed-size chunks from the given source stream.The returned stream is lazy and consumes the source stream as it is traversed. Closing the returned stream will also close the source stream.
The final partial chunk is included.
- Type Parameters:
T- element type- Parameters:
source- the source stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a stream of chunks as
List<T> - Throws:
NullPointerException- ifsourceisnullIllegalArgumentException- ifchunkSizeis less than1
-
streamOfChunks
public static <T> Stream<List<T>> streamOfChunks(Stream<T> source, int chunkSize, Chunking.RemainderPolicy remainderPolicy) Returns aStreamof fixed-size chunks from the given source stream, using the givenChunking.RemainderPolicy.The returned stream is lazy and consumes the source stream as it is traversed. Closing the returned stream will also close the source stream.
- Type Parameters:
T- element type- Parameters:
source- the source stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zeroremainderPolicy- how to handle the final partial chunk; must not benull- Returns:
- a stream of chunks as
List<T> - Throws:
NullPointerException- ifsourceorremainderPolicyisnullIllegalArgumentException- ifchunkSizeis less than1
-
forEachChunk
public static <T> void forEachChunk(Stream<T> source, int chunkSize, Consumer<? super List<T>> chunkHandler) Processes each fixed-size chunk from the given source stream using the provided consumer, without materializing all chunks in memory at once.This is a convenience wrapper around
streamOfChunks(Stream, int)for the common "stream-and-handle-chunks" use case:Chunking.forEachChunk( someStream, 100, chunk -> doSomethingWith(chunk) );The source stream is always closed when processing completes or if an exception is thrown.
- Type Parameters:
T- element type- Parameters:
source- the source stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zerochunkHandler- consumer that will be invoked once per emitted chunk; must not benull- Throws:
NullPointerException- ifsourceorchunkHandlerisnullIllegalArgumentException- ifchunkSizeis less than1
-
forEachChunk
public static <T> void forEachChunk(Stream<T> source, int chunkSize, Chunking.RemainderPolicy remainderPolicy, Consumer<? super List<T>> chunkHandler) Processes each fixed-size chunk from the given source stream using the provided consumer, with an explicitChunking.RemainderPolicy.- Type Parameters:
T- element type- Parameters:
source- the source stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zeroremainderPolicy- how to handle the final partial chunk; must not benullchunkHandler- consumer that will be invoked once per emitted chunk; must not benull- Throws:
NullPointerException- ifsource,remainderPolicy, orchunkHandlerisnullIllegalArgumentException- ifchunkSizeis less than1
-
slidingWindows
Returns aCollectorthat produces sliding windows of sizewindowSizewith stepstep.Only full windows are produced. For example:
[1,2,3,4] with windowSize=3, step=1 → [[1,2,3],[2,3,4]]
This collector respects the stream's encounter order and only makes sense for ordered streams; using an unordered stream will yield arbitrary windows.
- Type Parameters:
T- element type- Parameters:
windowSize- the size of each window; must be greater than zerostep- the step between window starting positions; must be greater than zero- Returns:
- a collector that accumulates elements into sliding windows
- Throws:
IllegalArgumentException- ifwindowSizeorstepis less than1
-
streamOfSlidingWindows
Returns aStreamof sliding windows of sizewindowSizewith step1.This is the streaming counterpart to
slidingWindows(int, int), emitting each window lazily without retaining all windows in memory.- Type Parameters:
T- element type- Parameters:
source- the source stream; must not benullwindowSize- the size of each window; must be greater than zero- Returns:
- a stream of windows as
List<T> - Throws:
NullPointerException- ifsourceisnullIllegalArgumentException- ifwindowSizeis less than1
-
streamOfSlidingWindows
public static <T> Stream<List<T>> streamOfSlidingWindows(Stream<T> source, int windowSize, int step) Returns aStreamof sliding windows of sizewindowSizewith the given step.Only full windows are produced. Semantics match
slidingWindows(int, int)but in a streaming form.- Type Parameters:
T- element type- Parameters:
source- the source stream; must not benullwindowSize- the size of each window; must be greater than zerostep- the step between window starting positions; must be greater than zero- Returns:
- a stream of windows as
List<T> - Throws:
NullPointerException- ifsourceisnullIllegalArgumentException- ifwindowSizeorstepis less than1
-
chunkedBy
public static <T> Collector<T,?, chunkedByList<List<T>>> (BiPredicate<? super T, ? super T> sameGroup) Returns aCollectorthat groups elements into chunks based on a boundary predicate.The first element always starts a new chunk. For each subsequent element
current, the predicate is called with(previous, current):- If it returns
true,currentis added to the current chunk. - If it returns
false, a new chunk is started withcurrent.
Ordering note: this collector defines its semantics in terms of adjacent elements in the stream's encounter order. If you supply an unordered or non-deterministic stream (for example, a parallel stream without forcing
.sequential()), the resulting chunk boundaries may be non-deterministic.- Type Parameters:
T- element type- Parameters:
sameGroup- predicate that determines whether two adjacent elements belong to the same chunk; must not benull- Returns:
- a collector that accumulates elements into boundary-based chunks
- Throws:
NullPointerException- ifsameGroupisnull
- If it returns
-
weightedChunks
public static <T> Collector<T,?, weightedChunksList<List<T>>> (long maxWeight, ToLongFunction<? super T> weigher) Returns aCollectorthat groups elements into chunks such that the sum of weights (as provided byweigher) within each chunk is <=maxWeight.The semantics are:
- Elements are processed in encounter order.
- If adding an element would exceed
maxWeight, a new chunk is started. - If a single element's weight is greater than
maxWeight, it forms a chunk by itself. - Negative weights are not allowed.
Ordering note: chunk composition is based purely on the stream's encounter order and the running sum of weights. If you collect from an unordered or non-deterministic stream, the grouping of elements into chunks may vary between runs.
- Type Parameters:
T- element type- Parameters:
maxWeight- maximum total weight per chunk; must be greater than zeroweigher- function that computes the weight of each element; must not benull- Returns:
- a collector that accumulates elements into weighted chunks
- Throws:
IllegalArgumentException- ifmaxWeightis less than1NullPointerException- ifweigherisnull
-
chunk
Chunks anIterableinto a list of lists, using its iteration order.The final partial chunk is included.
- Type Parameters:
T- the element type- Parameters:
iterable- the source iterable; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the iterable has no elements
- Throws:
NullPointerException- ifiterableisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
Chunks aSpliteratorinto a list of lists, using its traversal order.The final partial chunk is included.
- Type Parameters:
T- the element type- Parameters:
spliterator- the source spliterator; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the spliterator has no elements
- Throws:
NullPointerException- ifspliteratorisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
Chunks aCollectioninto a list of lists, using its iteration order.The final partial chunk is included.
- Type Parameters:
T- the element type- Parameters:
collection- the source collection; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the collection is empty
- Throws:
NullPointerException- ifcollectionisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
Chunks aStreaminto a list of lists and closes the stream.The final partial chunk is included.
- Type Parameters:
T- the element type- Parameters:
stream- the source stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the stream has no elements
- Throws:
NullPointerException- ifstreamisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
Varargs convenience method: chunks an array of elements.The final partial chunk is included.
- Type Parameters:
T- the element type- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zeroelements- the elements to chunk; must not benull- Returns:
- a list of chunks; possibly empty if no elements are provided
- Throws:
NullPointerException- ifelementsisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
- Parameters:
stream- the source int stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the stream has no elements
- Throws:
NullPointerException- ifstreamisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
- Parameters:
stream- the source long stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the stream has no elements
- Throws:
NullPointerException- ifstreamisnullIllegalArgumentException- ifchunkSizeis less than1
-
chunk
- Parameters:
stream- the source double stream; must not benullchunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a list of chunks; possibly empty if the stream has no elements
- Throws:
NullPointerException- ifstreamisnullIllegalArgumentException- ifchunkSizeis less than1
-
toIntChunks
Convenience collector forIntStreams.- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a collector that accumulates
Integervalues into fixed-size chunks - Throws:
IllegalArgumentException- ifchunkSizeis less than1
-
toLongChunks
Convenience collector forLongStreams.- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a collector that accumulates
Longvalues into fixed-size chunks - Throws:
IllegalArgumentException- ifchunkSizeis less than1
-
toDoubleChunks
Convenience collector forDoubleStreams.- Parameters:
chunkSize- the maximum number of elements in each chunk; must be greater than zero- Returns:
- a collector that accumulates
Doublevalues into fixed-size chunks - Throws:
IllegalArgumentException- ifchunkSizeis less than1
-