使用流将Java 2D数组转换为2D ArrayList [英] Java 2D array into 2D ArrayList with stream

查看:284
本文介绍了使用流将Java 2D数组转换为2D ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 Integer [] [] data 我要转换成 ArrayList< ArrayList< Integer>> ,所以我尝试使用流并提出以下行:

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));

但是最后一部分 collect(Collectors.toCollection(ArrayList< ArrayList< Integer> ;> :: new))给我一个错误,它无法转换 ArrayList< ArrayList< Integer>>到C

But the last part collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new)) gives me an error that it cannot convert ArrayList<ArrayList<Integer>> to C.

推荐答案

内部收集(Collectors.toList() 返回 List< Integer> ,而不是 ArrayList< Integer> ,所以你应该收集这些内部列表进入 ArrayList< List< Integer>>

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));

或者,使用 Collectors.toCollection(ArrayList< 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));

这篇关于使用流将Java 2D数组转换为2D ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆