Skip to content

Instantly share code, notes, and snippets.

@abop
Created March 2, 2021 07:17
Show Gist options
  • Save abop/91f5a10f9ba56fa867b68d85bf6b62b0 to your computer and use it in GitHub Desktop.
Save abop/91f5a10f9ba56fa867b68d85bf6b62b0 to your computer and use it in GitHub Desktop.
Partition list into equal parts, given the max size of each partition.
public static void main(String[] args) {
// [[1, 2, 3]]
System.out.println(partition(Arrays.asList(1, 2, 3), 4));
// [[1, 2, 3, 4]]
System.out.println(partition(Arrays.asList(1, 2, 3, 4), 4));
// [[1, 2, 3], [4, 5]]
System.out.println(partition(Arrays.asList(1, 2, 3, 4, 5), 4));
// [[1, 2, 3], [4, 5, 6]]
System.out.println(partition(Arrays.asList(1, 2, 3, 4, 5, 6), 4));
// [[1, 2, 3, 4], [5, 6, 7]]
System.out.println(partition(Arrays.asList(1, 2, 3, 4, 5, 6, 7), 4));
// [[1, 2, 3, 4], [5, 6, 7, 8]]
System.out.println(partition(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8), 4));
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
System.out.println(partition(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9), 4));
}
public static List<List<Integer>> partition(List<Integer> list, int maxN) {
final int size = list.size();
if (size == 0) {
return Lists.newArrayList();
}
final int partitionCount = (size - 1) / maxN + 1;
final int maxSizeInPartition = (size - 1) / partitionCount + 1;
return Lists.partition(list, maxSizeInPartition);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment