In Java streams is peek really only for debugging?

后端 未结 6 796
误落风尘
误落风尘 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:25

    Perhaps a rule of thumb should be that if you do use peek outside the "debug" scenario, you should only do so if you're sure of what the terminating and intermediate filtering conditions are. For example:

    return list.stream().map(foo->foo.getBar())
                        .peek(bar->bar.publish("HELLO"))
                        .collect(Collectors.toList());
    

    seems to be a valid case where you want, in one operation to transform all Foos to Bars and tell them all hello.

    Seems more efficient and elegant than something like:

    List bars = list.stream().map(foo->foo.getBar()).collect(Collectors.toList());
    bars.forEach(bar->bar.publish("HELLO"));
    return bars;
    

    and you don't end up iterating a collection twice.

提交回复
热议问题