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

Tags:

Java