I have a large file that contains a list of items.
I would like to create a batch of items, make an HTTP request with this batch (all of the items are needed as par
this is a pure java solution that's evaluated lazily.
public static Stream> partition(Stream stream, int batchSize){
List> currentBatch = new ArrayList>(); //just to make it mutable
currentBatch.add(new ArrayList(batchSize));
return Stream.concat(stream
.sequential()
.map(new Function>(){
public List apply(T t){
currentBatch.get(0).add(t);
return currentBatch.get(0).size() == batchSize ? currentBatch.set(0,new ArrayList<>(batchSize)): null;
}
}), Stream.generate(()->currentBatch.get(0).isEmpty()?null:currentBatch.get(0))
.limit(1)
).filter(Objects::nonNull);
}