Created
March 7, 2016 20:28
-
-
Save garcia-jj/e4afbf0eaeb66afb0033 to your computer and use it in GitHub Desktop.
Chunked streams (partitioning)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChunkedStream<T> { | |
private final List<T> elements; | |
private ChunkedStream(final List<T> elements) { | |
this.elements = elements; | |
} | |
public static <T> ChunkedStream<T> of(final List<T> elements) { | |
return new ChunkedStream<T>(elements); | |
} | |
public Stream<List<T>> stream(final int length) { | |
final int size = elements.size(); | |
if (elements.isEmpty()) { | |
return Stream.empty(); | |
} | |
final int chunks = (size - 1) / length; | |
return IntStream.range(0, chunks + 1).mapToObj(n -> elements.subList(n * length, (n == chunks) ? size : (n + 1) * length)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment