Java Streams learning path Level 1 This level ยท 5 of 25
Medium java streams

map versus flatMap

The 30 second answer

map is one-to-one: each element becomes one new element. flatMap is one-to-many: each element becomes a stream, and those streams are flattened into one. A typical example is turning a stream of orders into a stream of all line items. Java 16 also added mapMulti as an imperative alternative.

Could you say this in an interview?

map is one-to-one (Stream<T> โ†’ Stream<R>). flatMap maps each element to a stream and flattens (one-to-many), for example:

orders.stream().flatMap(o -> o.items().stream())

Java 16 added mapMulti as an imperative alternative when allocating many tiny streams is costly.

Sources (1)
  1. Stream.map / flatMap / mapMultidocs.oracle.com
Previous
Next