I wrote a generic utility method few days back for my own usage, which converts a List<List<T>> to T[][]. Here's the method. You can use it for your purpose:
public static <T> T[][] multiListToArray(final List<List<T>> listOfList,
final Class<T> classz) {
final T[][] array = (T[][]) Array.newInstance(classz, listOfList.size(), 0);
for (int i = 0; i < listOfList.size(); i++) {
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
}
return array;
}
There I've created the array using Array#newInstance() method, since you cannot create an array of type parameter T directly.
Since we're creating a 2-D array, and we don't yet know how many columns you will be having, I've given the column size as 0 initially. Anyways, the code is initializing each row with a new array inside the for loop. So, you don't need to worry about that.
This line:
array[i] = listOfList.get(i).toArray((T[]) Array.newInstance(classz, listOfList.get(i).size()));
uses the List#toArray(T[]) method to convert the inner list to an array, as you already did. I'm just passing an array as a parameter to the method so that the return value which I get is T[], which I can directly assign to the current row - array[i].
Now you can use this method as:
String[][] arr = multiListToArray(yourList, String.class);
Thanks to @arshaji, you can modify the generic method to pass the uninitialized array as 2nd parameter, instead of Class<T>:
public static <T> void multiListToArray(final List<List<T>> listOfList,
final T[][] arr) {
for (int i = 0; i < listOfList.size(); ++i) {
arr[i] = listOfList.get(i).toArray(arr[i]);
}
}
But then, you have to pass the array to this method like this:
List<List<String>> list = new ArrayList<>();
// Initialize list
String[][] arr = new String[list.size()][0];
multiListToArray(list, arr);
Note that, since now we are passing the array as argument, you no longer need to return it from your method. The modification done in the array will be reflected to the array in the calling code.