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

Ale*_*iam 6 java list java-8 java-stream

我试过这个代码(listArrayList<List<Integer>>):

list.stream().flatMap(Stream::of).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

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

Ous*_* D. 6

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

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

{{{1,2}}, {{3,4}}, {{5,6}}} -> flatMap -> {{1,2}, {3,4}, {5,6}}
// result after flatMap removes the stream of streams of streams to stream of streams
Run Code Online (Sandbox Code Playgroud)

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

{{1,2}, {3,4}, {5,6}}
Run Code Online (Sandbox Code Playgroud)

并把它变成:

{1,2,3,4,5,6}
Run Code Online (Sandbox Code Playgroud)

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

List<Integer> result = list.stream().flatMap(Collection::stream)
                           .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)