what does java8 stream map do here?

后端 未结 4 1669
栀梦
栀梦 2020-12-11 17:34

I was confused about the difference between map() and forEach() method in java8 stream. For instance,

List strings =          


        
4条回答
  •  独厮守ぢ
    2020-12-11 18:21

    The documentation for each instance method of Stream states whether the method is an intermediate operation, or a terminal operation. Only terminal operations will cause the stream to be evaluated. Intermediate operations may not be performed unless required by a downstream terminal operation.

    This can improve efficiency, especially when the terminal operation is a short-circuit operation, like findAny(). A pipeline with a complex set of intermediate operations doesn't need to be executed for additional elements after a matching element has been found.

    In your case, forEach() is a terminal operation; it causes the pipeline to be executed. map() is an intermediate operation; it doesn't have to do anything unless required by a downstream terminal operation.

提交回复
热议问题