liveBook · Manning

Stateful mapping operation

As explained in 100 Java Mistakes and How to Avoid Them

A stateful mapping operation produces an element using information retained from previously processed elements.

A stateful mapping operation retains the previous stream element while map() processes the current one. This violates the Stream API requirement that mapping functions be stateless. section 9.5

Adjacent-pair mapping

A pairMap utility stores prev, applies a BiFunction to prev and the current element, emits null for the first element, and removes it with skip(1). For "a", "b", "c", and "d", it aims to produce "a->b", "b->c", and "c->d". The assumption of left-to-right processing may work sequentially but breaks under parallel execution. section 9.5

Avoid the mistake by:

  • Following the Stream API contract instead of adding state to map() functions. section 9.5
  • Avoiding custom pairwise operations unless their sequential and parallel behavior is correctly implemented. section 9.5
  • Considering the StreamEx implementation when a dependable pairwise operation is required. section 9.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains retained state, ordering assumptions, and parallel failure, but stops short of implementing a correct general pairwise operation.
Examples
Uses a pairMap utility that transforms adjacent "a", "b", "c", and "d" elements into arrow-separated pairs.
What it assumes
Assumes familiarity with Java streams, map(), parallelization, and functional interfaces such as BiFunction.
What you can do after
Diagnose/debug stream utilities that depend on encounter order and avoid stateful map() functions in parallel-capable pipelines.
How it connects
Connects map(), intermediate operations, sequential streams, parallel streams, ordering, and StreamEx.

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.