-2

I want to split the array into multiple array with smaller size. Below is the code i am using for get array values.

itemtbldata = itemtbldata.substring(1, itemtbldata.length()-1);
System.out.println("itemtbldata   "+itemtbldata);
String[] itemcell = itemtbldata.split(",");
System.out.println(itemcell.length);

For example itemcell has below values

itemcell = [renu,1252,ed,dev,kalam,8562,ed,dev]

now i want to get as below. Please someone help

arr1 = [renu,1252,ed,dev]
arr2 = [kalam,8562,ed,dev]
Rob
  • 11,492
  • 14
  • 59
  • 94
kavi
  • 163
  • 1
  • 9

2 Answers2

1

You can use System.arraycopy like this (see working demo http://rextester.com/RZA81274)

int finalRowSize = 4; //Set here the chunks size
String[] itemcell = {"renu","1252","ed","dev","kalam","8562","ed","dev"};
String[][] result =  monoToBidi(itemcell,itemcell.length / finalRowSize, finalRowSize); 

public static String[][] monoToBidi(final String[] array, final int rows, final int cols){        
        String[][] bidi = new String[rows][cols];
        for ( int i = 0; i < rows; i++ )
            System.arraycopy(array, (i*cols), bidi[i], 0, cols);        
        return bidi;
}
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
0

Here is a manually written Java approach:

public static void main(String[] args)
{
    int max = 4;
    String[] data = { "renu", "1252", "ed", "dev", "kalam", "8562", "ed", "dev", "hi", };

    // use ceiling so 9 / 4 = 3. (round shouldn't be necessary, but just for safety, here it is)
    int numOfArrays = (int)Math.round(Math.ceil(data.length / (float)max));
    String[][] data2 = new String[numOfArrays][];

    // loop over all instances except the last one (as that one might be smaller than the max
    for (int i = 0; i < numOfArrays-1; i++)
    {
        data2[i] = new String[max];
        System.arraycopy(data, i*max, data2[i], 0, max);
    }
    if (numOfArrays > 0)
    {
        int index = numOfArrays-1;
        int length = data.length % max;
        data2[index] = new String[length];
        System.arraycopy(data, index*max, data2[index], 0, length);
    }

    System.out.println(Arrays.deepToString(data2));
}
Wietlol
  • 1,001
  • 1
  • 10
  • 25