Skip to content

Instantly share code, notes, and snippets.

@charlie
Created June 1, 2011 22:11
Show Gist options
  • Save charlie/1003473 to your computer and use it in GitHub Desktop.
Save charlie/1003473 to your computer and use it in GitHub Desktop.
public static <T> List partition(List<T> list, int numPartitions, int minPerPartition) {
ArrayList<List> partitions = new ArrayList<List>();
int i = 0;
int n = list.size();
int numPerPartition = new BigDecimal(n).divide(new BigDecimal(numPartitions), 0, RoundingMode.CEILING).intValue();
if (numPerPartition < minPerPartition) {
numPerPartition = minPerPartition;
}
while(i < n) {
int j = 0;
List<T> partition = new ArrayList<T>();
while (j < numPerPartition && (i + j) < n) {
partition.add(list.get(i + j));
j += 1;
}
partitions.add(partition);
i += numPerPartition;
}
return partitions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment