如何使用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 时,它将返回现有列表的新流.
那就是当你执行 {{{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()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |