I have a Collection of type String that contains anywhere from 0 to 10k values. I am looking for an elegant or reusable way to write a method that takes in a Collection of type String and a batch size and splits the collection into smaller chunks of the provided batch size.
The best solution I could come up with is:
private static <T> Collection<Collection<T>> getBatches( List<T> collection, int batchSize ){
return IntStream.iterate(0, i -> i < collection.size(), i -> i + batchSize)
.mapToObj(i -> collection.subList(i, Math.min(i + batchSize, collection.size())))
.collect(Collectors.toList());
}
Some concerns:
- I would like to take in a Collection of type String and return either a Collection of Collection of type String or a List of Collection of type String.
- I wonder if there are any cons or edge cases that this logic will not work for.