Search code examples
javacollectionschunks

How to chunk a Collection of Strings in java


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:

  1. 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.
  2. I wonder if there are any cons or edge cases that this logic will not work for.

Solution

  • 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);