Chriz
Chriz

Reputation: 1

Convert a List<List<string>> to string[]

whats the shortest way to convert a <List<List<string>> to a string-array?

I tried with a foreach loop, but in this case I don't have an index for my array, so I can't fill up the array!? :-(

        foreach (List<string> list in myList)
        {
            foreach (string s in list)
            {
                Array[s] = list.ToArray;
            }
        }

Upvotes: 0

Views: 187

Answers (6)

Parthi P
Parthi P

Reputation: 65

Try like this,

List<String> list1 = new ArrayList<String>();

list1.add("aa");

list1.add("bb");

List<String> list2 = new ArrayList<String>();

list2.add("cc");

list2.add("dd");

list2.add("ee");

List<List<String>> arrL = new ArrayList<List<String>>();

arrL.add(list1);

arrL.add(list2);

List<String> strList = new ArrayList<String>();

for (List<String> list : arrL)

{ strList.addAll(list); }

String []strArray = new String[strList.size()];

strList.toArray(strArray);

for (String string : strArray)

{ System.out.println(string); }

Upvotes: 0

elsco
elsco

Reputation: 1

List<List<String>> lisfOfList = new ArrayList<List<String>>();

List<String> result = new ArrayList<String>();
for(List<String> list : lisfOfList){
    result.addAll(list);
}

String[] s = result.toArray(new String[result.size()]);

Upvotes: 0

FazoM
FazoM

Reputation: 4956

First you need to know how big the array needs to be (this is because Arrays in Java can't be dynamic; can't change their size dynamically):

int max = 0;
for(List<String> list : myList)
{
   max += list.size();
}
String[] array = new String[max];

Then use your foreach loop (please note, it has different syntax) with an additional variable to keep current index:

int i = 0;
for(List<string> list : myList)
{
    for(String s : list)
    {
        array[i++] = s;
    }
}

Please also note how String is spelled.

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

First, calculate the size of the String[] array.

int size = 0;
for(List list : myList)
{
   size += list.size();
}
String[] array = new String[size];

Then, fulfill the array with all the strings in each of the lists:

int i = 0;
for (List<String> list : myList) {
    for (String s : list) {
        array[i++] = s;
    }
}

Upvotes: 1

Mohamad MohamadPoor
Mohamad MohamadPoor

Reputation: 1340

you can use something like this :

int i=0;
foreach (List<string> list in myList)
        {
            foreach (string s in list)
            {
                Array[i] = s;
                i++;
            }
        }

Upvotes: 0

nhaarman
nhaarman

Reputation: 100468

Use for(int i=0; i<myList.size(); i++){ ... }

Upvotes: 0

Related Questions