Edit: the original solution below does not work, since java stream does not allow calling skip or limit more than once on a same stream. I ended up simple processing like
final AtomicInteger counter = new AtomicInteger();
List<T> entityBatch = new ArrayList<>();
entityStream.forEach(entity -> {
if (counter.intValue() = batchSize) {
processBatch(entityBatch);
entityBatch.clear();
counter.set(0);
}
entityBatch.add(entity);
counter.incrementAndGet();
});
if (!entityBatch.isEmpty()) {
processBatch(entityBatch);
}
Original solution:
It looks like I found the way to do that:
<T> Stream<List<T>> batchStream(Stream<T> stream, int batchSize) {
return Stream.iterate(stream, s -> s.skip(batchSize)).map(s -> s.limit(batchSize).collect(toList()));
}