Java 2D 数组通过流转换为 2D ArrayList

标签 java arrays arraylist java-8 java-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 .

最佳答案

内在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/

相关文章:

java - E00011 - 访问被拒绝。您无权调用交易详情 API。 - 在 Aithorize.net

java - 为什么我的 IntelliJ 项目上的运行功能不起作用?它是灰色的

java - Android 应用程序中 setText 的空对象引用

java - 迁移到 Struts 2.5.16 导致 log4 问题

java - 很难在一系列对象中找到最低价格

c++ - Python 的 "in"运算符的 C++ 等价物是什么?

java - 当我输入数字时如何得到不同的结果?

java : remove words from ArrayList<String>

javascript - 合并数组,为什么我的输入数组发生了变化?

Java ArrayList indexOf 泛型类型