如何使用Streams将2D列表转换为1D列表?

我试过这段代码(列表是ArrayList< List< Integer>>):
list.stream().flatMap(Stream::of).collect(Collectors.toList());

但它没有做任何事情;该列表仍然是2D列表.如何将此2D列表转换为1D列表?

解决方法

您仍在接收列表列表的原因是因为当您应用 Stream::of时,它将返回现有列表的新流.

那就是当你执行Stream::of就像拥有{{{1,2}},{{3,4}},{{5,6}}}那么当你执行flatMap时就像这样做:

{{{1,6}}} -> flatMap -> {{1,2},{3,4},{5,6}}
// result after flatMap removes the stream of streams of streams to stream of streams

相反,您可以使用.flatMap(Collection :: stream)来获取流的流,例如:

{{1,6}}

并把它变成:

{1,2,3,4,5,6}

因此,您可以将当前的解决方案更改为:

List<Integer> result = list.stream().flatMap(Collection::stream)
                           .collect(Collectors.toList());

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...