Stream<Stream>: flatMap vs. reduce

This question already has an answer here:

  • Why filter() after flatMap() is “not completely” lazy in Java streams? 6 answers

  • 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:

  • In flatMap , the second stream is only considered when the first is depleted.
  • In 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.

    链接地址: http://www.djcxy.com/p/34756.html

    上一篇: 代码不会查看隐藏的行以添加包含跟踪编号的行

    下一篇: Stream <Stream>:flatMap与reduce