Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static <T> Stream<List<T>> batches(List<T> source, 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));
- }
- public static void main(String[] args) {
- List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
- System.out.println("By 3:");
- batches(list, 3).forEach(System.out::println);
- System.out.println("By 4:");
- batches(list, 4).forEach(System.out::println);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement