Convert two dimensional array to List in java?

This is a nice way of doing it for any two-dimensional array, assuming you want them in the following order:

[[array[0]-elems], [array[1]elems]...]

public <T> List<T> twoDArrayToList(T[][] twoDArray) {
    List<T> list = new ArrayList<T>();
    for (T[] array : twoDArray) {
        list.addAll(Arrays.asList(array));
    }
    return list;
}

Since java-8

List<Foo> collection = Arrays.stream(array)  //'array' is two-dimensional
    .flatMap(Arrays::stream)
    .collect(Collectors.toList());

for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
        yourList.add(foosArray[i][j]);

I think other tricks are unnecessary, because, anyway, they'll use this solution.


This can be done using Java 8 stream API this way:

String[][] dataSet = new String[][] {{...}, {...}, ...};
List<List<String>> list = Arrays.stream(dataSet)
                               .map(Arrays::asList)
                               .collect(Collectors.toList());

Basically, you do three things:

  • Convert the 2-d array into stream
  • Map each element in stream (which should be an array) into a List using Arrays::asList API
  • Reduce the stream into a new List