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
.
The inner collect(Collectors.toList()
returns a List<Integer>
, not ArrayList<Integer>
, so you should collect these inner List
s 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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.