Stream<Stream>: flatMap vs. reduce
This question already has an answer here:
From the implementation of flatMap in openJDK, what I understand is that flatMap
pushes the whole content of the incoming stream downstream:
result.sequential().forEach(downstreamAsInt);
On the other hand, Stream::concat
seems to be handling the pull and not sending everything at once.
I suspect that your test does not show the full picture:
flatMap
, the second stream is only considered when the first is depleted. reduce
, all the streams are being pushed in the final concatenated stream, because the reduced object does not make sense until all the content of the input stream is consumed. Which means using one or the other depends on how complex your inputs are. If you have an infinite Stream<Stream<Integer>>
, reduce will never finish.