Junior — Middle
What is the main difference between using the map and flatMap methods in the Stream API when processing data streams?
sobes.tech AI
Answer from AI
The main difference between the map and flatMap methods in the Stream API is:
maptransforms each element of the stream into another object, returning a stream of these objects.flatMaptransforms each element into a stream (Stream) of objects, and then "flattens" (flattens) these streams into a single common stream.
Example:
List<List<String>> listOfLists = List.of(
List.of("a", "b"),
List.of("c", "d")
);
// map will return Stream<List<String>>
Stream<List<String>> streamOfLists = listOfLists.stream().map(list -> list);
// flatMap will return Stream<String>, "flattening" nested lists
Stream<String> streamOfStrings = listOfLists.stream().flatMap(list -> list.stream());
Thus, flatMap is useful when each element of the original stream corresponds to multiple elements in the resulting stream, and you need to obtain a single stream of these elements.