In which cases Stream operations should be stateful?

前端 未结 4 785
轮回少年
轮回少年 2021-01-01 03:30

In the javaodoc for the stream package, at the end of the section Parallelism, I read:

Most stream operations accept parameters that des

4条回答
  •  独厮守ぢ
    2021-01-01 04:29

    Examples of stateful stream lambdas:

    • collect(Collector): The Collector is by definition stateful, since it has to collect all the elements in a collection (state).
    • forEach(Consumer): The Consumer is by definition stateful, well except if it's a black hole (no-op).
    • peek(Consumer): The Consumer is by definition stateful, because why peek if not to store it somewhere (e.g. log).

    So, Collector and Consumer are two lambda interfaces that by definition are stateful.

    All the others, e.g. Predicate, Function, UnaryOperator, BinaryOperator, and Comparator, should be stateless.

提交回复
热议问题