Java 2D Array in 2D ArrayList with Stream

So, I have Integer[][] dataone that I want to convert to 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.

+2
source share
1 answer

The inner one collect(Collectors.toList()returns a List<Integer>, and not ArrayList<Integer>, so you must put these inner ones Listin 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));

Alternatively, use Collectors.toCollection(ArrayList<Integer>::new)to collect 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));
+4
source

Source: https://habr.com/ru/post/1678517/


All Articles