Reputation: 484
I have a requirement wherein i should write a method of type String[]
and return the same.But the implementation that i have, uses and returns List<List<String>>
.Also the List<List<String>>
gets and returns values from the database and the values are not known prior to add them to the String[]
directly.The list can also be of a huge size to accomodate it in an String[]
. How to get this conversion done.
Upvotes: 1
Views: 1561
Reputation: 25950
Take a look at this code:
public static String[] myMethod(ArrayList<ArrayList<String>> list)
{
int dim1 = list.size();
int total=0;
for(int i=0; i< dim1; i++)
total += list.get(i).size();
String[] result = new String[total];
int index = 0;
for(int i=0; i<dim1; i++)
{
int dim2 = list.get(i).size();
for(int j=0; j<dim2; j++)
{
result[index] = list.get(i).get(j);
index++;
}
}
return result;
}
Run this test code:
public static void main(String[] args)
{
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
ArrayList<String> list3 = new ArrayList<String>();
list1.add("first of first");
list1.add("second of first");
list1.add("third of first");
list2.add("first of second");
list3.add("first of third");
list3.add("second of third");
ArrayList<ArrayList<String>> superList = new ArrayList<ArrayList<String>>();
superList.add(list1);
superList.add(list2);
superList.add(list3);
String[] output = myMethod(superList);
for(int i=0; i<output.length; i++)
System.out.println(output[i]);
}
Upvotes: -2
Reputation: 80633
This should work just fine. Though if you can return your embedded list structure that would be even better:
final List<String> resultList = new ArrayList<String>(64000);
final List<List<String>> mainList = yourFuncWhichReturnsEmbeddedLists();
for(final List<String> subList: mainList) {
resultList.addAll(subList);
}
final String[] resultArr = subList.toArray(new String[0]);
Upvotes: 3