Java tutorial
//package com.java2s; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { public static <T> Stream<List<T>> chunked(Iterable<T> iterable, int chunkSize) { List<T> list = toList(iterable); return batches(list, chunkSize); } public static <T> List<T> toList(Iterable<T> iterable) { List<T> temp = new ArrayList<>(); iterable.forEach(temp::add); return temp; } 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)); } }