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:
Have a look at this example idea:
final List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);
final int chunkSize = 3;
final AtomicInteger counter = new AtomicInteger();
final Collection<List<Integer>> result = numbers.stream()
.collect(Collectors.groupingBy(it ->
counter.getAndIncrement() / chunkSize))
.values();
System.out.println(result);