How do I convert a 2D list to a 1D list using streams?

I tried this code (the list is ArrayList < list < integer > >):

list.stream().flatMap(Stream::of).collect(Collectors.toList());

But it did nothing; The list is still a 2D list How do I convert this 2D list to a 1D list?

Solution

The reason you are still receiving the list is because when you apply stream:: of, it will return a new stream of the existing list

That is, when you execute stream:: of, it's like having {{1,2}, {{3,4}, {{5,6}}, so when you execute flatmap, it's like this:

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

Instead, you can use Flatmap (Collection:: Stream) to obtain the stream of the stream, for example:

{{1,6}}

And turn it into:

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

Therefore, you can change the current solution to:

List<Integer> result = list.stream().flatMap(Collection::stream)
                           .collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>