How might I convert List<List<String>>
to String[][]
?
I've played around with the solutions provided here but not having much luck.
Any help would be appreciated.
How might I convert List<List<String>>
to String[][]
?
I've played around with the solutions provided here but not having much luck.
Any help would be appreciated.
You can not just apply outer.toArray(...)
because that would give you an array of lists, List<String>[]
.
You have to first convert all the inner lists before you can collect them into your resulting data structure. There is no utility method available that can do this automatically for you, but it is fairly easy to do it yourself.
Streams are a very good candidate for this. Just stream the outer list, convert the inner lists and then use toArray
as provided by Stream
.
String[][] result = outer.stream() // Stream<List<String>>
.map(inner -> inner.toArray(String[]::new)) // Stream<String[]>
.toArray(String[][]::new);
You can follow the exact same idea also with a more traditional manual approach where you setup your target outer array, loop over the inner lists, convert them and collect them into your array.
String[][] result = new String[outer.size()];
int i = 0;
for (List<String> inner : outer) {
result[i] = inner.toArray(String[]::new);
i++;
}