liveBook · Manning

Pairmap

As explained in 100 Java Mistakes and How to Avoid Them

pairMap is a utility operation that maps each pair of adjacent stream elements to a resulting element.

pairMap maps each adjacent pair of stream elements to a result by retaining the previous element. A typical implementation stores state inside map() and removes the first output with skip(1). section 9.5

Adjacent-element mapping

Given a, b, c, and d, mapping each pair with (left, right) -> left + "->" + right produces a->b, b->c, and c->d.

The implementation violates the Stream API contract because map() functions must be stateless. It assumes left-to-right processing: sequential streams may appear to work, although that order is not guaranteed, while parallel streams are completely broken. Calling sequential() inside pairMap() cannot prevent a client from later calling parallel(). section 9.5

Avoid the failure by following these rules:

  • Test stream-consuming or stream-producing utilities after applying parallel(). section 9.5
  • Use a correctly implemented third-party operation such as StreamEx when dependencies permit; otherwise prefer a conventional loop. section 9.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the stateful implementation and its sequential assumption, then stops short of designing a correct parallel operation.
Examples
Uses a four-element string stream to produce three labeled adjacent-pair results.
What it assumes
Assumes familiarity with Java streams, map(), skip(), sequential execution, parallel execution, and BiFunction.
What you can do after
Diagnose/debug pairMap implementations by checking statefulness, ordering assumptions, and behavior after parallel().
How it connects
Connects pairMap to Stream API, map(), skip(), BiFunction, sequential streams, parallel streams, 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.