SteelReed

Search

Search posts, questions…

Java CoreQuestion 31 / 43

Junior

How does a Stream work: intermediate vs terminal operations, laziness, and map vs flatMap?

Short answer

A stream has a source, intermediate steps (filter, map) that are only recorded, and one terminal step (toList, count) that actually runs it. That is laziness.

triggerslimit, findFirstSource: orders.stream()filter, map, flatMaponly recordedTerminal operationtoList, countEach elementgoes through pipelineStop early

3 points to say:

  1. Without a terminal step, nothing runs.
  2. map turns 1 into 1, flatMap turns 1 into many and flattens.
  3. A stream can be used only once.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.