Search code examples
javalistmatrix

How can I convert a List<int[]> to a 2D array?


I have a List of arrays declared like this :

List<int[]> ls = new ArrayList<int[]>();

Here I am trying to keep a list with arrays like this : [ [1,2,3] ,[2,3],[4,5] ]

To add an array to this list I do this in a for loop:

int[] a = new int[2];
a[0] = arr[i];
a[1] = arr[i]+k;
ls.add(a);

I want to convert this list of arrays in a matrix that has 1 rows and list.size as colums like this :

[[0, -1], [-1, -2], [2, 1], [1, 0]]

How can I do this?

Thanks!


Solution

  • Simple, invoke toArray:

    // new double-dimension int array
    //                   | conversion here
    //                   |                  | specifying 1st dimension's size as list's 
    //                   |                  | size
    int[][] converted = ls.toArray(new int[ls.size()][]);
    
    // test it
    System.out.println(Arrays.deepToString(converted));