Course contentsShow
← Java
Lesson 1439 of 2,87032. Streams API: Intermediate OperationsFree lesson

flatMap vs map: When to Use Each

Comparing map and flatMap behavior, understanding when nested streams require flattening.

flatMap vs map: When to Use Each

You'll learn when to choose map versus flatMap for different transformation scenarios.

Both map and flatMap transform stream elements, but they handle the shape of your results very differently.

The Core Difference

Use map when each input element transforms into exactly one output element. The transformation is one-to-one:

  • Converting strings to uppercase
  • Extracting object properties
  • Simple calculations

Use flatMap when each input element transforms into zero, one, or multiple output elements that need to be "unpacked" into a single flat stream:

  • Breaking sentences into words
  • Unwrapping nested collections
  • Expanding optional values

The Stream Type Clue

The key signal is what your transformation function returns:

  • map(Function<T, R>) → Your function returns R (a regular object)
  • flatMap(Function<T, Stream<R>>) → Your function returns Stream<R> (already a stream)

If map produces Stream<Stream<R>> (nested streams), you need flatMap instead.

Practical Decision Guide

Ask yourself: "Does my transformation create a collection or stream that needs flattening?"

  • No flattening needed? → Use map
  • Need to flatten nested structures? → Use flatMap

Example scenario: Given a list of orders, each containing multiple items:

  • To get order totals: use map (one order → one total)
  • To get all items across orders: use flatMap (one order → many items, flattened)

Key Takeaway: Use map for one-to-one transformations; use flatMap when your transformation produces multiple elements per input that need flattening into a single stream.