Java Split Array into Multiple Arrays

Sometimes we need to split the array into multiple arrays based on the size in java. In other words, divide the array into pieces of length n. The output returns consecutive sub-arrays of an array, each of the same size (final may be smaller).
We can achieve our goal with the help of the Arrays.copyRange() method. First, we will understand the question with the help of examples.

Read Also: Java Array Interview Questions and Answers

Suppose we have been given the below array:

//Given Array
int[] inputArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

Output:

//Partition Array into size of 2
[1,2] [3,4] [5,6] [7,8] [9,10] [11]
//Partition Array into size of 3
[1,2,3] [4,5,6] [7,8,9] [10,11]
//Partition Array into size of 4
[1,2,3,4] [5,6,7,8] [9,10,11]

Solution:


1. Using Java 8
2. Using Guava library

1. Using Java8


We will use Arrays.copyOfRange() method to divide an array into subarrays in Java. Arrays.copyOfRange(int[] original, int from, int to) method copies the specified range of the specified array into a new array.

import java.util.*;
import java.util.stream.*;


public class SplitArrayToSubArrays{
    
    public static void main(String args[]) {
        int[] inputArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        int chunkSize = 5;
        
        int[][] output = splitArray(inputArray, chunkSize);
        for (int[] x : output)
            System.out.println(Arrays.toString(x));
    }
    
    public static int[][] splitArray(int[] inputArray, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((int) Math.ceil((double) inputArray.length / chunkSize))
                .mapToObj(j -> Arrays.copyOfRange(inputArray, j, Math.min(inputArray.length, j + chunkSize)))
                .toArray(int[][]::new);
    }
}

Output:
[1,2,3,4,5] [6,7,8,9,10] [11]


2. Using Guava Library


If you are using 3rd party jars in the project, then you can achieve the same result by adding the Guava library. Use Guava library's Lists.partition() method as shown below:

    int[] inputArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    List<Integer> listToSplit = Arrays.asList(inputArray);
    int chunkSize = 3;
    Lists.partition(listToSplit, chunkSize);

That's all for today, please mention in comments in case you have any questions related to Split Array into Multiple Arrays in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry