javamultidimensional-arrayarraylistindexingvarying

Convert ArrayList into 2D array containing varying lengths of arrays


So I have:

ArrayList<ArrayList<String>> 

Which contains an x number of ArrayLists which contain another y number of Strings.. To demonstrate:

Index 0:
  String 1
  String 2
  String 3
Index 1:
  String 4
Index 2:
Index 3:
  String 5
  String 6

Where index refers to the array index containing a string.

How can I transform this into a 2D array which looks like:

{{String1, String2, String3},{String4}, {}, {String5, String6}}

Thank you so much.


Solution

  • String[][] array = new String[arrayList.size()][];
    for (int i = 0; i < arrayList.size(); i++) {
        ArrayList<String> row = arrayList.get(i);
        array[i] = row.toArray(new String[row.size()]);
    }
    

    where arrayList is your ArrayList<ArrayList<String>> (or any List<List<String>>, change the first line inside the for loop accordingly)