简体   繁体   中英

Convert List<List<String>> to String[]

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.

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]);

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]);                  
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM