Junior — Middle
Can you explain what the flatMap method is and how it differs from map?
sobes.tech AI
Answer from AI
The map method is applied to a collection and transforms each element, returning a new collection with elements corresponding to the results of the function.
flatMap first applies a function that returns a collection (or stream) for each element, and then "flattens" all these collections into a single stream or list.
Example in Java with streams:
List<List<String>> list = Arrays.asList(
Arrays.asList("a", "b"),
Arrays.asList("c", "d")
);
// map returns Stream<List<String>>
Stream<List<String>> mapped = list.stream()
.map(innerList -> innerList.stream().map(String::toUpperCase).collect(Collectors.toList()));
// flatMap returns Stream<String>
Stream<String> flatMapped = list.stream()
.flatMap(innerList -> innerList.stream().map(String::toUpperCase));
// flatMapped can be collected into a single list
List<String> result = flatMapped.collect(Collectors.toList()); // ["A", "B", "C", "D"]
Thus, flatMap is useful when the function returns nested collections, and you need to obtain a flat structure.