所以我有一个 Integer[][] data
我想将其转换为 ArrayList<ArrayList<Integer>>
,所以我尝试使用流并得出以下行:
ArrayList<ArrayList<Integer>> col = Arrays.stream(data).map(i -> Arrays.stream(i).collect(Collectors.toList())).collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));
但是最后一部分collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new))
给我一个错误,它无法转换 ArrayList<ArrayList<Integer>> to C
.
最佳答案
内在collect(Collectors.toList()
返回 List<Integer>
,不是ArrayList<Integer>
,所以你应该收集这些内部List
进入 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));
或者,使用 Collectors.toCollection(ArrayList<Integer>::new)
收集内部元素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));
关于Java 2D 数组通过流转换为 2D ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36999907/