加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:59:49 所属栏目:Java 来源:网络整理
导读:我试过这段代码(列表是ArrayList List Integer): list.stream().flatMap(Stream::of).collect(Collectors.toList()); 但它没有做任何事情;该列表仍然是2D列表.如何将此2D列表转换为1D列表? 解决方法 您仍在接收列表列表的原因是因为当您应用 Stream::of 时
我试过这段代码(列表是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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读