39

Below is the example of the code snippet which needs help

Example:

[1,2,3,4,5]
  • if the chunk size is 1, [1] and [2] and [3] and [4] and [5]
  • if the chunk size is 2, [1,2] and [3,4] and [5]
  • if the chunk size is 3, [1,2,3] and [4,5]
  • if the chunk size is 4, [1,2,3,4] and [5]

Java (from comment):

int counter = 0;
for (int i=0; i<array.length; i++) {
  if (count == chunksize) {
    //do something and initialize
    counter = 0;
  }
  counter++; 
}
5
  • 22
    If the chunk size is 1, why isn't the result [1] and [2] and [3] and [4] and [5] ? Commented Jan 9, 2015 at 9:07
  • 1
    have you tried something? Can you share what you tried if you already did? Commented Jan 9, 2015 at 9:09
  • you can ignore the chunk 1, i just gave an example..we can check the size and the chunk is equal...when the case is equal we don't need chunks at all Commented Jan 9, 2015 at 9:09
  • 7
    Well, we can ignore it, or you can provide correct examples ... Commented Jan 9, 2015 at 9:10
  • int counter = 0; for(int i=0; i<array.length; i++) { if(count == chunksize) { //do something and initialize counter = 0; } counter++; Commented Jan 9, 2015 at 9:11

20 Answers 20

37

You can use Arrays.copyOfRange(int[] original, int from, int to) The code could be something like this:

int chunk = 2; // chunk size to divide
for(int i=0;i<original.length;i+=chunk){
    System.out.println(Arrays.toString(Arrays.copyOfRange(original, i, Math.min(original.length,i+chunk))));
}          
Sign up to request clarification or add additional context in comments.

4 Comments

so for random chunk need one more loop??
What do you mean by random chunk?
random chunk means if i want for all chunk values..(1,2,3,4)
Yes, Just replace chunk=2 part by a for loop.
30

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]

1 Comment

Solid implementation. Actually gives a full and correct answer to the question at hand.
11

If you don't mind importing Google Guava and converting to a List, there is a method for partitioning Lists:

https://google.github.io/guava/releases/27.1-jre/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-

The following may achieve the desired result:

List<Integer> listToBeSplit = Arrays.asList(sourceArray);
int chunkSize = 3;
Lists.partition(listToBeSplit, chunkSize);

1 Comment

There is also an Apache Commons Collections ListUtils.partition() method.
5

Using pure Java 8:

public class Chunk {
    public static void main(String[] args) {
        int[] input = {1,2,3,4,78,999,-1,456};
        int chunkSize = 3;

        int[][] chunked = chunk(input, chunkSize);

        Arrays.stream(chunked)
                .map(Arrays::toString)
                    .forEach(System.out::println);
    }

    public static int[][] chunk(int[] input, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((long) Math.ceil((double) input.length / chunkSize))
                .mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input.length ? input.length : j + chunkSize))
                .toArray(int[][]::new);
    }
}

[1, 2, 3]
[4, 78, 999]
[-1, 456]

1 Comment

j + chunkSize > input.length ? input.length : j + chunkSize can be replaced with Math.min(j + chunkSize, input.length)
4
        import java.util.Arrays;

        public class ArrayChunk {

            public static void main(String[] args) {

                int[] array = {1,2,3,4,5};

                
                 int[][] chunks1 = ArrayChunk(array, 1);
                 print(chunks1);
                 int[][] chunks2 = ArrayChunk(array, 2);
                 print(chunks2);
                 int[][] chunks3 = ArrayChunk(array, 3);
                 print(chunks3);

                 
                 
            }

            public static int[][] ArrayChunk(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;
            }

            private static void print(int[][] output) {
                //
                System.out.println("======================");
                for (int[] x : output)
                    System.out.println(Arrays.toString(x));
            }
            

        }



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

Comments

2

Try this,

Iterate it and check to give the chunk size.

int chunkSize = userInput;

// iterate and check the condition

char[] resultArray = Arrays.copyOfRange(inputArray, start, end);
start = start + end;  // check whether the start will exceeds the length of the array

Comments

1
public static int[][] chunkArray(int[] array, int chunkSize) {
        // first we need to get number of chunks by dividing length by chunkSize.
        int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
// we declare 2d array to save in the chunks
        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;
    }

Comments

1
   for(int i=0;i<list.size();){
    ArrayList<Integer>row = new ArrayList<Integer>();
    int k=0;
    while(k < chunksize){
        chunk.add(list.get(i));
        i++;
        k++;
    }
    System.out.println(chunk);
    nestedlist.add(chunk);
}   

where list is a 1 dimension array and chunk is a nested array of size chunksize

1 Comment

Your solution wont work in some cases. What if list.size() is 1 and chunksize is 3
0

In general you could use Arrays.copyOfRange to copy

1 Comment

Please add essential information from the link in your answer. Link-only answers should be avoided.
0

This should do the trick

public static List<String> split(String string, int chunk) {
    Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
            + "}[0-9]+)|[0-9]+");
    Matcher matcher = pattern.matcher(string);

    List<String> result = new ArrayList<String>();
    while (matcher.find())
        result.add("[" + matcher.group() + "]");

    return result;
}

Test code:

for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
    System.out.println("test for chunk size: " + chunkSize);
    for (String string : split("[1,2,3,4,5]", chunkSize))
        System.out.format("\t%s\n", string);
}

Output:

test for chunk size: 1
    [1]
    [2]
    [3]
    [4]
    [5]
test for chunk size: 2
    [1,2]
    [3,4]
    [5]
test for chunk size: 3
    [1,2,3]
    [4]
    [5]
test for chunk size: 4
    [1,2,3,4]
    [5]
test for chunk size: 5
    [1,2,3,4,5]

Comments

0
public class ArrayChunk {
    public static void main(String[] args) {

        String[][] chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 2);
        System.out.println("Array with chunk size 2");
        Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));

        chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 3);
        System.out.println("Array with chunk size 3");
        Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));

        chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 4);
        System.out.println("Array with chunk size 4");
        Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));

        chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 5);
        System.out.println("Array with chunk size 5");
        Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
    }

    private static String[][] chunkArray(String[] array, int chunkSize) {
        int chunkedSize = (int) Math.ceil((double) array.length / chunkSize); // chunked array size
        String[][] chunked = new String[chunkedSize][chunkSize];
        for (int index = 0; index < chunkedSize; index++) {
            String[] chunk = new String[chunkSize]; // small array
            System.arraycopy(array, index * chunkSize, chunk, 0, Math.min(chunkSize, array.length - index * chunkSize));
            chunked[index] = chunk;
        }
        return chunked;
    }
}

Output

Array with chunk size 2
1,2
3,4
5,6
7,8
9,null

Array with chunk size 3
1,2,3
4,5,6
7,8,9

Array with chunk size 4
1,2,3,4
5,6,7,8
9,null,null,null

Array with chunk size 5
1,2,3,4,5
6,7,8,9,null

Comments

0

Easy way to do so,

    int loopcount = employeeList.size() / constCount;
    int leftcount = employeeList.size() % constCount;
    for (int i = 0; i < loopcount - 1; i++) {
        //query.setParameterList("values"+i, employeeList.subList(tempCount, tempCount + constCount));

        System.out.println(employeeList.subList(tempCount, tempCount + constCount));
        tempCount = tempCount + 1000;
    }

Comments

0
public class SplitArrayIntoChunks {
  public static void main(String[] args) {
    int[] in = {1,2,3,4,5};
    chunks(in, 2);
  }

  private static void chunks(int[] in, int chunkSize) {
    List<int[]> outList = new ArrayList<>();

    int i = 0;

    while (i < in.length) {
        int[] out = Arrays.copyOfRange(in, i, Math.min(i + chunkSize, in.length));
        outList.add(out);
        out = new int[chunkSize + 1];
        i += chunkSize;
    }

    for (int[] ol: outList) {
        System.out.print("[");
        Arrays.stream(ol).forEach(System.out::print);
        System.out.println("]");
    }
  }
}

// Result: [12] [34] [5]

Comments

0
    let array = [1, 2, 3, 4, 5, 6, 7, 8];
    let idx = 0;
    let count = 0;
    let tempList = [];
    let resultList = [];
    let splitSize = 2
    
    while (idx <= array.length)
    {
        tempList.push(array[idx++]);
        count++;
        if (count == splitSize)
        {
            resultList.push(tempList);
            tempList = [];
            count = 0;
        }
    }
    if (!tempList.length)
    {
        resultList.push(tempList);
    }
console.log(resultList);

Comments

0

This can be done in a few lines of code

int i=0;
while (i<array.length) {
    System.out.println(Arrays.toString(Arrays.copyOfRange(array, i, Math.min(array.length, i+chunkSize))));
    i+=chunkSize;
}

Comments

0

Q.Split the array into chunks with a specified size? Answer: public class SplitArray {

public static void main(String[] args) {
        int[] original = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int splitSize = 3;
        
        /* expected Output 
        [0, 1, 2]
        [3, 4, 5]
        [6, 7, 8]
        [9]
        */
    
        List<int[]> list = splitArray(original, splitSize);
        list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));

}
public static List<int[]> splitArray(int[] array, int splitSize) {
    List<int[]> result = new ArrayList<>();
    int len=array.length;
    int arr[] = null;
    int size = splitSize;
    int k=0;
    for(int i=0;i<array.length;i++) {
        if(k==0)
        arr=new int[size];
        arr[k]=array[i];
        k++;
        if(k>size-1) {
            k=0;
            result.add(arr);
            len=len-size;
            if(len<splitSize) {
                size=len;
            }
        }
    }
    return result;
}

}

Comments

0

As an exercise, I was curious about a solution that uses the more declarative style that's available from Java 8 with Streams.

First, here's a solution using streams, which works with a generic List<T> (not what the question asked for) of objects of type T to be 'chunked' :

   public static <T> List<List<T>> chunkify(List<T> src, int chunkSize) {
      AtomicInteger index = new AtomicInteger(0);
      return src.stream()
              .collect(Collectors.groupingBy(x -> index.getAndIncrement() / chunkSize)) // (1)
              .entrySet().stream()                         // (2)
              .sorted(Map.Entry.comparingByKey())          // (3)
              .map(Map.Entry::getValue)                    // (4)
              .collect(Collectors.toList());               // (5)
   }

For example, if we start with a src list of three integers:

List<Integer>
[1, 2, 3]

then (1) groupingBy with a chunkSize of 2 will provide a Map :

Map<Integer, List<Integer>>
0 -> [1, 2], 1 -> [3]

(because index.getAndIncrement() / chunkSize will return [0, 0, 1], for the calls for the three integers in src)

(2) entrySet().stream() provides a Stream<Map.Entry>:

Stream<Entry<Integer, List<Integer>>>
{key: 0, value: [1, 2]}, {key: 1, value: [3]} 

(3) sorted(Map.Entry.comparingKey()) ensures the correct ordering, which is not guaranteed (I think!) by the output of the groupingBy method, nor by entrySet which returns a Set

(4) map(Map.Entry::getValue) extracts the chunks from the Stream of Map.Entry values:

Stream<List<Integer>>
[1, 2], [3]

(5) collect is used to convert this to a List<List<Integer>>


But the original question specified that

  • the input was an array of int, and
  • the result was some kind of collection if int arrays

So, here's a solution that takes an int[] and returns a List<int[]>. It uses the same algorithm as above, but now adds the

  • conversion between int[] and Stream<Integer> at the start, and
  • conversion between Stream<List<Integer>> and Stream<int[]> at the end.
   public static List<int[]> chunkify(int[] src, int chunkSize) {
      AtomicInteger index = new AtomicInteger(0);
      return Arrays.stream(src)
            .boxed()
            .collect(Collectors.groupingBy(x -> index.getAndIncrement() / chunkSize))
            .entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .map(Map.Entry::getValue)
            .map(list -> list.stream().mapToInt(Integer::intValue).toArray())
            .collect(Collectors.toList());
   }

This solution is made ugly (IMO) by the conversions at the start and the end.

As I said, this was an exercise (for me!), and one in which I was not interested in the performance of the algorithm.

Comments

0

Here is the full solution using Arrays.copyOfRange() .I tried to remove complexity little bit

 public class DivideArrayIntoChunks {

    public static void main(String[] args) {

        int arr[] = new int[] {1,2,3,4,5,6,7};
        int chunkSize =2;
        int[] [] a = getChunks(arr, chunkSize);
        for (int [] i : a) {
            System.out.print(Arrays.toString(i));
        }


    }
    public static int[][] getChunks(int[] arr, int chunkSize) {

        int rest = arr.length % chunkSize; // space for any remaining chunks less than chunk size. either 0 or 1

        int chunks = arr.length/chunkSize;
        int totalChunks = chunks + (rest > 0 ? 1 : 0);
        int a[][] = new int[totalChunks][];  
    


        for (int i = 0, j = 0; i+rest <= arr.length; i += chunkSize, j++) {
           
            a[j] = Arrays.copyOfRange(arr, i, i+chunkSize);
        }
        if(rest > 0) {           

            a[totalChunks-1] = Arrays.copyOfRange(arr, arr.length-rest, arr.length);
        }


        return a;
    }
}

Comments

0
 public static int chunk(int[] input, int chunkSize) {
    int size = 0;
    int index = 0;
    int[] newCharArray = new int[chunkSize];
    for (int i = 0; i < input.length; i++) {
        if (index == chunkSize) {
            size++;
            index = 0;
            i--;
            System.out.println(Arrays.toString(newCharArray));
            newCharArray = new int[chunkSize];
        } else {
            newCharArray[index] = input[i];
            index++;
        }
        if (i == input.length - 1) {
            System.out.println(Arrays.toString(newCharArray));
            size++;
        }
    }

    return size;
}

1 Comment

it will return how many chunks was generated & print every chunk as well
0

Stream Gatherers

In Java 24 there is a new feature being added to the stream API, Stream Gatherers. It is a preview feature in JDK 23. Using the windowFixed stream gatherer, the code to split an array into chunks can be made shorter and more readable, at the expense of some boxing and unboxing of the ints.

int[][] chunkArray(int[] array, int chunkSize) {
    return Arrays.stream(array)
        .boxed()
        .gather(Gatherers.windowFixed(chunkSize))
        .map(window -> window.stream().mapToInt(x -> x).toArray())
        .toArray(int[][]::new);
}

Explanation: Arrays.stream produces a stream of int, boxed() turns it into a stream of Integer, the windowFixed gatherer does the work of partitioning the stream into chunks, each one a List<Integer>, the map turns each one into an int[] so that we have a Stream<int[]>, and the toArray with the two-dimensional int array constructor reference gives us our int[][] result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.