问题
So I have an Integer[][] data that I want to convert into an ArrayList<ArrayList<Integer>>, so I tried using streams and came up with the following line:
ArrayList<ArrayList<Integer>> col = Arrays.stream(data).map(i -> Arrays.stream(i).collect(Collectors.toList())).collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));
But the last part collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new)) gives me an error that it cannot convert ArrayList<ArrayList<Integer>> to C.
回答1:
The inner collect(Collectors.toList() returns a List<Integer>, not ArrayList<Integer>, so you should collect these inner Lists into an ArrayList<List<Integer>> :
ArrayList<List<Integer>> col =
Arrays.stream(data)
.map(i -> Arrays.stream(i)
.collect(Collectors.toList()))
.collect(Collectors.toCollection(ArrayList<List<Integer>>::new));
Alternately, use Collectors.toCollection(ArrayList<Integer>::new) to collect the elements of the inner Stream :
ArrayList<ArrayList<Integer>> col =
Arrays.stream(data)
.map(i -> Arrays.stream(i)
.collect(Collectors.toCollection(ArrayList<Integer>::new)))
.collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));
来源:https://stackoverflow.com/questions/36999907/java-2d-array-into-2d-arraylist-with-stream