Skip to content

Instantly share code, notes, and snippets.

@Fullplate
Created July 11, 2014 04:29
Show Gist options
  • Save Fullplate/6a57c3aa6f34130cf03e to your computer and use it in GitHub Desktop.
Save Fullplate/6a57c3aa6f34130cf03e to your computer and use it in GitHub Desktop.
[Java] Split list into batches of max size n
private static <T> List<List<T>> batchList(List<T> inputList, final int maxSize) {
List<List<T>> sublists = new ArrayList<>();
final int size = inputList.size();
for (int i = 0; i < size; i += maxSize) {
// Math.min... size will be smaller than i + maxSize for the last batch (unless perfectly divisible),
// including the first batch if size is smaller than max size
sublists.add(new ArrayList<>(inputList.subList(i, Math.min(size, i + maxSize))));
}
return sublists;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment