Convert nested list to 2d array
There is no simple builtin way to do what you want because your list.toArray()
can return only array of elements stored in list which in your case would also be lists.
Simplest solution would be creating two dimensional array and filling it with results of toArray
from each of nested lists.
String[][] array = new String[list.size()][];
int i = 0;
for (List<String> nestedList : list) {
array[i++] = nestedList.toArray(new String[nestedList.size()]);
}
(you can shorten this code if you are using Java 8 with streams just like Alex did)
You could do this:
String[][] array = list.stream()
.map(l -> l.stream().toArray(String[]::new))
.toArray(String[][]::new);
It creates a Stream<List<String>>
from your list of lists, then from that uses map
to replace each of the lists with an array of strings which results in a Stream<String[]>
, then finally calls toArray
(with a generator function, instead of the no-parameter version) on that to produce the String[][]
.