Search code examples
javamultidimensional-arraynested-lists

Convert nested list to 2d array


I'm trying to convert a nested list into a 2d array.

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

list.add(Arrays.asList("a", "b", "c"));
list.add(Arrays.asList("dd"));
list.add(Arrays.asList("eee", "fff"));

I want to make this a String[][]. I've tried the following:

String[][] array = (String[][]) list.toArray();      // ClassCastException

String[][] array = list.toArray(new String[3][3]);   // ArrayStoreException

String[][] array = (String[][]) list.stream()        // ClassCastException
    .map(sublist -> (String[]) sublist.toArray()).toArray();

Is there a way that works? Note that I won't know the size of the list until runtime, and it may be jagged.


Solution

  • There is no simple builtin way to do what you want because your list.toArray() can return only array of elements stored in list which in your case would also be lists.

    Simplest solution would be creating two dimensional array and filling it with results of toArray from each of nested lists.

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

    (you can shorten this code if you are using Java 8 with streams just like Alex did)