我试过这段代码( list
是 ArrayList<List<Integer>>
):
list.stream().flatMap(Stream::of).collect(Collectors.toList());
但它什么也没做;该列表仍然是一个二维列表。如何将此二维列表转换为一维列表?
最佳答案
您仍然收到列表的原因是因为当您申请 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
相反,您可以使用 .flatMap(Collection::stream)
获取流的流,例如:
{{1,2}, {3,4}, {5,6}}
并将其变成:
{1,2,3,4,5,6}
因此,您可以将当前的解决方案更改为:
List<Integer> result = list.stream().flatMap(Collection::stream)
.collect(Collectors.toList());
关于java - 如何使用 Streams 将二维列表转换为一维列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251460/