Skip to content

Instantly share code, notes, and snippets.

@garcia-jj
Created March 7, 2016 20:28
Show Gist options
  • Save garcia-jj/e4afbf0eaeb66afb0033 to your computer and use it in GitHub Desktop.
Save garcia-jj/e4afbf0eaeb66afb0033 to your computer and use it in GitHub Desktop.
Chunked streams (partitioning)
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