Junior — Middle
What is the difference between map and flatMap methods in Java Stream API and what are their usage features?
sobes.tech AI
Answer from AI
The map and flatMap methods in Java Stream API are used for transforming stream elements, but they work differently:
-
maptakes a function that transforms each element of the stream into one other element. As a result, it produces a stream with the same number of elements but of a different type or form. -
flatMaptakes a function that transforms each element into a stream (Stream) of elements, and then flattens ("spreads") all these streams into one common stream. This is useful when one element needs to produce multiple elements.
Example:
List<String> words = Arrays.asList("hello", "world");
// map: transform each word into its length
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList()); // [5, 5]
// flatMap: split each word into letters and combine all letters into one stream
List<String> letters = words.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.collect(Collectors.toList()); // [h, e, l, l, o, w, o, r, l, d]
Usage features:
mapis suitable for simple element-to-element transformation.flatMapis needed when one element should produce multiple elements, and nested structures need to be "flattened".