Skip to content

Instantly share code, notes, and snippets.

@jomoespe
Created May 25, 2016 09:42
Show Gist options
  • Save jomoespe/d3f0b8f332f3d78cb0534e4695a28b01 to your computer and use it in GitHub Desktop.
Save jomoespe/d3f0b8f332f3d78cb0534e4695a28b01 to your computer and use it in GitHub Desktop.
Class with a utility method to divide a list in diferent chunks and returns a Stream of lists
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamUtil {
public static <T> Stream<List<T>> buffer(final List<T> source, final int length) {
if (length <= 0) throw new IllegalArgumentException("length = " + length);
int size = source.size();
if (size <= 0) return Stream.empty();
int fullChunks = (size - 1) / length;
return IntStream.range(0, fullChunks + 1).mapToObj(
n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment