what does java8 stream map do here?

后端 未结 4 1681
栀梦
栀梦 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:18

    The difference is this:

    • The idea of forEach() is to "work" on each element of the underlying collection (by having a side effect) whereas
    • map() is about applying a method on each object and putting the result of that into a new stream

    That is also the reason why your stream().map() doesn't result in something - because you throw away the new stream created by the map() call!

    In that sense, the signatures of the two methods tell you that:

    void forEach(BiConsumer action)
    

    Performs the given action for each entry in this map until all entries have been processed

    versus

      Stream map(Function mapper)
    

    Returns a stream consisting of the results of applying the given function to the elements of this stream.

    And for the record: only map() is a stream method - forEach() exists for both, streams and Collections/Iterables.

提交回复
热议问题