简体   繁体   English

将Java 2D数组转换为带有流的2D ArrayList

[英]Java 2D array into 2D ArrayList with stream

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: 所以我有一个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));

But the last part collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new)) gives me an error that it cannot convert ArrayList<ArrayList<Integer>> to C . 但是最后一部分collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new))给我一个错误,它无法将ArrayList<ArrayList<Integer>> to C转换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>> : 内部的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));

Alternately, use Collectors.toCollection(ArrayList<Integer>::new) to collect the elements of the inner Stream : 或者,使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM