What is the difference between `map()` and `flatMap()` in Java Streams?
The map()
and flatMap()
methods in Java Streams are used for transforming data, but they differ in how they handle the transformation.
map()
- Purpose: The
map()
method is used to transform each element of the stream into another object. - Behavior: It takes a function that maps each element to a new element (which could be of a different type).
- Result: Returns a stream of the transformed elements.
List<String> words = Arrays.asList("Java", "Python", "C++");
List<Integer> lengths = words.stream()
.map(String::length) // Maps each word to its length
.collect(Collectors.toList());
flatMap()
- Purpose: The
flatMap()
method is used when each element in the stream could be transformed into multiple elements, and those multiple elements need to be flattened into a single stream. - Behavior: It takes a function that maps each element to a stream of elements (not just a single element).
- Result: Returns a stream that is flattened (i.e., it “flattens” multiple nested streams into one).
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("Java", "Python"),
Arrays.asList("C++", "JavaScript")
);
List<String> flatList = nestedList.stream()
.flatMap(List::stream) // Flattens nested lists into one stream
.collect(Collectors.toList());
Key Differences
map()
: Transforms each element into one new element.flatMap()
: Transforms each element into a stream of elements and then flattens them into a single stream.
In summary, map()
is used for one-to-one transformations, while flatMap()
is used when you need to transform each element into multiple elements and flatten the result.