Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split an array into multiple subarrays of size n in java

I want to split an array of integers into multiple subArrays of size n.How can this be achieved?

I tried using following way but it gives OutOfMemoryError

import java.util.*;

public class SplittingArraysIntoSubArrays {

    public static void main(String[] args) {
        int[] arrr = {1,3,2,5,4,6,8,13};
        List<int[]> arrayList = new ArrayList<>();
        int arrayLength = arrr.length;
        int n =3;
        int counter=1;
        
        while(n*counter<arrayLength) {
            arrayList.add(Arrays.copyOf(arrr, 3));
            counter++;
        }       
        System.out.println("Done");
    }   
}


Below is the output i get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{1,3,2},{1,3,2}]

>Solution :

You need to keep track of your position in the array arrr. You also need to check that there are 3 elements when you copy the (up to) three elements into a new array. And you need to copy ranges of elements from the array, so Arrays.copyOfRange(int[], int, int) would be more appropriate. Putting that together might look something like,

int[] arrr = { 1, 3, 2, 5, 4, 6, 8, 13 };
List<int[]> arrayList = new ArrayList<>();
for (int i = 0; i < arrr.length; i += 3) {
    int n = Math.min(3, arrr.length - i);
    arrayList.add(Arrays.copyOfRange(arrr, i, i + n));
}
for (int[] arr : arrayList) {
    System.out.println(Arrays.toString(arr));
}
System.out.println("Done");

Which outputs

[1, 3, 2]
[5, 4, 6]
[8, 13]
Done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading