Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert two dimensional array to List in java?

Tags:

java

I have am X n two dimensional array of an Object say Foo. So I have Foo[][] foosArray. What is the best way to convert this into a List<Foo> in Java?

like image 774
Inquisitive Avatar asked Jul 12 '12 08:07

Inquisitive


2 Answers

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; } 
like image 78
Keppil Avatar answered Oct 08 '22 23:10

Keppil


Since java-8

List<Foo> collection = Arrays.stream(array)  //'array' is two-dimensional     .flatMap(Arrays::stream)     .collect(Collectors.toList()); 
like image 39
Tomasz Mularczyk Avatar answered Oct 08 '22 22:10

Tomasz Mularczyk