Skip to content

Instantly share code, notes, and snippets.

@lesleh
Last active March 10, 2024 20:16
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lesleh/7724554 to your computer and use it in GitHub Desktop.
Save lesleh/7724554 to your computer and use it in GitHub Desktop.
Java function to split an array into chunks of equal size. The last chunk may be smaller than the rest.
// Example usage:
//
// int[] numbers = {1, 2, 3, 4, 5, 6, 7};
// int[][] chunks = chunkArray(numbers, 3);
//
// chunks now contains [
// [1, 2, 3],
// [4, 5, 6],
// [7]
// ]
public static int[][] chunkArray(int[] array, int chunkSize) {
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
int[][] output = new int[numOfChunks][];
for(int i = 0; i < numOfChunks; ++i) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
return output;
}
@javamuc
Copy link

javamuc commented May 9, 2016

Please add license information.

@willtonkin
Copy link

Very helpful. Thanks for this

@Dashing-Daniel-Li
Copy link

what is the licence for this?
Is it mit

@SpexGuy
Copy link

SpexGuy commented Mar 16, 2018

As long as your array length isn't close to Integer.MAX_VALUE, using
int numOfChunks = (array.length + chunkSize - 1) / chunkSize;
avoids the integer->double->integer conversion, and removes any worries about rounding error along with it.

@GitVishwa
Copy link

How About 2-Dimensional Array?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment