java - How can I convert List<List<String>> into String[][]? -
in project have list contains lists of strings (list<list<string>>) , have convert list array of string arrays (string[][]).
if had single list<string> (for example mylist) convert string[]:
string[] myarray = new string[mylist.size()]; myarray = mylist.toarray(myarray); but in case have lots of list of string inside list (of list of strings). how can this? i've spent lots of time didn't find solution..
i wrote generic utility method few days own usage, converts list<list<t>> t[][]. here's method. can use 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); (int = 0; < listoflist.size(); i++) { array[i] = listoflist.get(i).toarray((t[]) array.newinstance(classz, listoflist.get(i).size())); } return array; } there i've created array using array#newinstance() method, since cannot create array of type parameter t directly.
since we're creating 2-d array, , don't yet know how many columns having, i've given column size 0 initially. anyways, code initializing each row new array inside loop. so, don't need worry that.
this line:
array[i] = listoflist.get(i).toarray((t[]) array.newinstance(classz, listoflist.get(i).size())); uses list#toarray(t[]) method convert inner list array, did. i'm passing array parameter method return value t[], can directly assign current row - array[i].
now can use method as:
string[][] arr = multilisttoarray(yourlist, string.class); thanks @arshaji, can modify generic method pass uninitialized array 2nd parameter, instead of class<t>:
public static <t> void multilisttoarray(final list<list<t>> listoflist, final t[][] arr) { (int = 0; < listoflist.size(); ++i) { arr[i] = listoflist.get(i).toarray(arr[i]); } } but then, have pass array method this:
list<list<string>> list = new arraylist<>(); // initialize list string[][] arr = new string[list.size()][0]; multilisttoarray(list, arr); note that, since passing array argument, no longer need return method. modification done in array reflected array in calling code.
Comments
Post a Comment