Sobes.tech
Junior — Middle

Explain the differences between the 'map' and 'flatMap' methods when working with collections or data streams.

sobes.tech AI

Answer from AI

The map method is applied to a collection or stream and transforms each element, returning a new collection with elements corresponding to the transformation results. Each input element is transformed into exactly one output element.

The flatMap method first applies a function that returns a collection (or stream) for each element, and then "flattens" all these nested collections into a single flat collection. This is useful when the transformation function returns multiple elements for each input.

Example in Swift:

let numbers = [1, 2, 3]

// map: multiply each element by 2
let mapped = numbers.map { [$0, $0 * 2] }
// mapped: [[1, 2], [2, 4], [3, 6]]

// flatMap: transform and flatten
let flatMapped = numbers.flatMap { [$0, $0 * 2] }
// flatMapped: [1, 2, 2, 4, 3, 6]

Thus, flatMap is useful when the function returns a collection, and you want to obtain a single combined collection without nesting.

Explain the differences between the 'map' and… - sobes.tech