All about streams - iamshaqir/resources GitHub Wiki

Stateless and Stateful Stream Processing

Stateless Operations in Java Streams

  • A stateless operation in a Java Stream is one where the processing of an element does not depend on the state of any other element that has passed through the stream or the state of the stream itself.
  • The result of processing one element doesn't affect how subsequent elements are processed
  • They can be processed in parallel easily because there are no dependencies between elements.
  • Examples:map(), filter(), flatMap(), forEach()

Stateful Operations in Java Streams

  • A stateful operation in a Java Stream is one where the processing of an element depends on the state of the stream or the results of processing previous elements. This often involves maintaining some internal state.
  • The order of elements can matter.
  • They are harder to parallelize efficiently because of the dependencies between elements or the need to maintain a shared, mutable state.
  • Examples: distinct(), sorted(), limit(), skip(), reduce(), collect(). (Note: reduce and collect can be considered stateful in their accumulation, but are designed to handle parallelism safely.)