Could you explain the difference between map and flatMap?
💡 Model Answer
In functional programming, both map and flatMap transform collections, but they differ in how they handle nested results. Map applies a function to each element, producing a new collection of the same depth. For example, mapping a list of integers to their squares yields a list of integers. FlatMap, on the other hand, applies a function that returns a collection for each element and then flattens the resulting nested collections into a single-level collection. This is useful when the transformation can produce multiple outputs per input. For instance, mapping a list of sentences to words using flatMap will produce a single list of all words. In Java Streams, map returns a Stream<T> from Stream<T> to Stream<R>, while flatMap returns a Stream<R> from Stream<T> to Stream<R> by flattening inner streams. In Scala, map returns a Seq[B] from Seq[A] to Seq[B], whereas flatMap returns a Seq[B] by concatenating the sequences produced by the function. Choosing between them depends on whether the transformation yields a single value per input (use map) or multiple values (use flatMap).
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500