簡體   English   中英

將Java 2D數組轉換為帶有流的2D ArrayList

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

所以我有一個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轉換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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM