In Java streams is peek really only for debugging?

后端 未结 6 657
误落风尘
误落风尘 2020-11-22 03:40

I\'m reading up about Java streams and discovering new things as I go along. One of the new things I found was the peek() function. Almost everything I\'ve read

6条回答
  •  攒了一身酷
    2020-11-22 04:29

    I would say that peek provides the ability to decentralize code that can mutate stream objects, or modify global state (based on them), instead of stuffing everything into a simple or composed function passed to a terminal method.

    Now the question might be: should we mutate stream objects or change global state from within functions in functional style java programming?

    If the answer to any of the the above 2 questions is yes (or: in some cases yes) then peek() is definitely not only for debugging purposes, for the same reason that forEach() isn't only for debugging purposes.

    For me when choosing between forEach() and peek(), is choosing the following: Do I want pieces of code that mutate stream objects to be attached to a composable, or do I want them to attach directly to stream?

    I think peek() will better pair with java9 methods. e.g. takeWhile() may need to decide when to stop iteration based on an already mutated object, so paring it with forEach() would not have the same effect.

    P.S. I have not referenced map() anywhere because in case we want to mutate objects (or global state), rather than generating new objects, it works exactly like peek().

提交回复
热议问题