Java – is there a preferred way to collect list streams into flat lists?

I wonder if there is a preferred way to flow from a list to a collection of elements that contain all the lists in the stream

final Stream<List<Integer>> stream = Stream.empty();
final List<Integer> one = stream.collect(ArrayList::new,ArrayList::addAll,ArrayList::addAll);
final List<Integer> two = stream.flatMap(List::stream).collect(Collectors.toList());

The second option looks better to me, but I guess the first is more efficient in parallel flow Is there any further argument for one of these two methods?

Solution

The main difference is that flatmap is intermediate operation, The collection is terminal operation

Therefore, if you want to perform other operations rather than collect immediately, flatmap is the only way to process the flattening flow project

In addition, the collection (ArrayList:: new, ArrayList:: addall, ArrayList:: addall) is very difficult to read because you have two identical methods that reference ArrayList:: addall with completely different semantics

Your guess about parallel processing is wrong The first has less parallel processing power because it relies on ArrayList Add applies to flow items (sub lists) that cannot be decomposed into parallel sub steps Conversely, if the specific list encountered in the stream supports it, it is applied to the collectors of flatmap Tolist () can perform parallel processing of sublist items However, this will be relevant only if you have a fairly large sublist

The only disadvantage of flatmap is the creation of intermediate flow, which will increase the overhead when you have many very small sub lists

But in your example, the stream is empty, so it doesn't matter (SCNR)

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
分享
二维码
< <上一篇
下一篇>>