'Convert List of Lists to int array

I have input of list of lists which i want to convert into int array which can help for my logic

list of Lists "lst" has input [[1,0,1],[1,1,0],[0,0,1]]

output array should be like {{1,0,1},{1,1,0},{0,0,1}}

int[] arr = new int[lst.size()];

for(int i=0;i<lst.size();i++){
    for(int j=0;j<lst.size();j++){
        arr[i] =  lst.get(i).get(j);
    }
}


Solution 1:[1]

Here are two ways.

The data

List<List<Integer>> list = List.of(List.of(1,0,1),
                                   List.of(1,1,0),
                                   List.of(0,0,1));
  • allocate an Array of arrays for the number of rows.
  • iterate over the rows of the data.
  • create an array to hold the inner array contents
  • fill it and assign to the array of arrays.
int[][] arr = new int[list.size()][];
for (int i = 0; i < list.size(); i++) {
    List<Integer> lst = list.get(i);
    int [] temp = new int[lst.size()];
    for (int k = 0; k < lst.size(); k++) {
        temp[k] = lst.get(k);
    }
    arr[i] = temp;
}

System.out.println(Arrays.deepToString(arr));

Or

  • stream the lists of lists
  • then stream each of those lists, mapping to an int and creating an array.
  • the put those arrays in an Array of arrays.
int[][] arr = list.stream()
               .map(ls->ls.stream().mapToInt(a->a).toArray())
               .toArray(int[][]::new);

System.out.println(Arrays.deepToString(arr));

Both print

[[1, 0, 1], [1, 1, 0], [0, 0, 1]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WJS