Java 2D array into 2D ArrayList with stream

吃可爱长大的小学妹 提交于 2020-01-02 13:44:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!