简体   繁体   中英

stateful and stateless methods of stream

In the interface Stream :

The intermediate operations are classifiable in stateful and stateless. They impact the result of a parallel Stream.

Only two terminal operations are nondeterministic methods: findAny() and forEach(Consumer). They impact the result of a parallel Stream.

The intermediate stateless operations could have a side-effect if they execute a lazy operation. This impact the result of a parallel Stream.

The intermediate operations are classifiable in:

Stateful

  • distinct()
  • sorted()
  • limit (long l)
  • skip (long l)

Stateless

  • map (Function f)
  • flatMap (Function f)
  • filter (Predicate p)
  • peek (Consumer c)

These are my two question:

  1. Stateless intermediate methods

    • If I call stateless intermediate methods on parallel stream + nondeterministic forEach(), I will obtain the same result of sequential stream, but with different order.
    • If I call stateless intermediate methods on parallel stream + nondeterministic findAny(), I will obtain an unpredictable result.
    • If I call stateless intermediate methods on parallel stream + normal terminal operation, I will obtain the same result of sequential stream.
    • If I call stateless intermediate methods on parallel stream + normal terminal operation with side-effect, I will obtain an unpredictable result.
  2. Stateful intermediate methods

    • If I call stateful intermediate methods + nondeterministic forEach(), I will obtain the same result of a sequential stream, but with different order.
    • If I call stateful intermediate methods + nondeterministic findAny(), I will obtain an unpredictable result.
    • If I call stateful intermediate methods + normal terminal operation, I will obtain the same result of a sequential stream.

Are these rules correct?

  1. The order of a Stream elements is "encounter order", except if I call the BaseStream method: unordered(). Does the order of the elements impact the results of a stream (in the presence of stateful or stateless methods)? If yes, how?

Thanks a lot!

A.

I guess both conditions 1 and 2 are true. I want to add some operations.

reduce also is part of the stateful operation.

forEach is part of the stateless operations.

Please note that stateless operations can become stateful if they create side effects.

The third statement is not totally correct. If a stream is ordered and we process it in parallel, the stream will remain ordered when used with the stateless operations. That's why we need to call the method unordered() on the stream to make it unordered and improve the efficiency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM