How to split a string array into small chunk arrays in java?

前端 未结 12 1939
春和景丽
春和景丽 2020-12-05 05:15

Below is the example of the code snippet which needs the help

Example:

[1,2,3,4,5]
  • if the chunk size is 1,
12条回答
  •  一生所求
    2020-12-05 05:40

    Just stumbled upon this post after encountering the same question. Here is how I solved it (I used Arrays.copyOfRange():

    public static int[][] splitArray(int[] arrayToSplit, int chunkSize){
        if(chunkSize<=0){
            return null;  // just in case :)
        }
        // first we have to check if the array can be split in multiple 
        // arrays of equal 'chunk' size
        int rest = arrayToSplit.length % chunkSize;  // if rest>0 then our last array will have less elements than the others 
        // then we check in how many arrays we can split our input array
        int chunks = arrayToSplit.length / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for the 'rest'
        // now we know how many arrays we need and create our result array
        int[][] arrays = new int[chunks][];
        // we create our resulting arrays by copying the corresponding 
        // part from the input array. If we have a rest (rest>0), then
        // the last array will have less elements than the others. This 
        // needs to be handled separately, so we iterate 1 times less.
        for(int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++){
            // this copies 'chunk' times 'chunkSize' elements into a new array
            arrays[i] = Arrays.copyOfRange(arrayToSplit, i * chunkSize, i * chunkSize + chunkSize);
        }
        if(rest > 0){ // only when we have a rest
            // we copy the remaining elements into the last chunk
            arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) * chunkSize, (chunks - 1) * chunkSize + rest);
        }
        return arrays; // that's it
    }
    

    And the results:

    chunkSize = 1
    [1]
    [2]
    [3]
    [4]
    [5]
    
    chunkSize = 2
    [1, 2]
    [3, 4]
    [5]
    
    chunkSize = 3
    [1, 2, 3]
    [4, 5]
    
    chunkSize = 4
    [1, 2, 3, 4]
    [5]
    
    chunkSize = 5
    [1, 2, 3, 4, 5]
    
    chunkSize = 6
    [1, 2, 3, 4, 5]
    

提交回复
热议问题