Both map()
and flatMap()
are used for transformation in Java Streams, but they behave differently when handling nested structures (like Lists of Lists).
Feature | map() | flatMap() |
---|---|---|
Purpose | Transforms each element individually | Flattens and transforms nested structures |
Output Type | Produces a Stream of Streams (nested) | Produces a flattened Stream |
Use Case | When each element is transformed independently | When each element contains collections and needs flattening |
Common Example | Convert elements (e.g., List of Strings to uppercase) | Convert a List of Lists into a single List |
1. map()
Example (No Flattening)
It applies a function to each element, without flattening nested structures.
Example: Convert Each String to Uppercase
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample {
public static void main(String[] args) {
List words = Arrays.asList("java", "stream", "map");
// Transform each word to uppercase
List result = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result);
}
}
Output
[JAVA, STREAM, MAP]
map()
keeps the structure intact, transforming elements but not merging them.
2. flatMap()
Example (Flattening a Nested List)
It flattens multiple lists into a single stream before applying transformation.
Example: Flatten a List of Lists
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FlatMapExample {
public static void main(String[] args) {
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("java", "python"),
Arrays.asList("c++", "javascript"),
Arrays.asList("go", "rust")
);
// Flatten and collect into a single list
List<String> flattenedList = listOfLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList);
}
}
Output
[java, python, c++, javascript, go, rust]
flatMap()
combines nested elements into a single list.
List<List<String>>
→ List<String>
3. Key Difference in map()
vs flatMap()
Output
If we use map()
instead of flatMap()
, we get List of Streams, not a single list.
List<Stream<String>> mapped = listOfLists.stream()
.map(List::stream)
.collect(Collectors.toList());
Output (Nested Streams, Not Flattened):
[Stream@1a2b3c4d, Stream@5e6f7g8h, Stream@9i0j1k2l]
flatMap()
solves this by merging the streams into one.
4. When to Use map()
vs. flatMap()
Scenario | Use map() | Use flatMap() |
---|---|---|
Transforming elements one by one | Yes | No |
Dealing with nested collections | No | Yes |
Convert List of Strings to uppercase | Yes | No |
Flattening List of Lists | No | Yes |
Conclusion
Use map()
when transforming individual elements.
Use flatMap()
when working with nested structures and needing flattening.