map vs flatMap (Java 8 Streams)
- map transforms one element into one element
- flatMap transforms one element into multiple elements and flattens the result
If mapping creates a nested structure, use flatMap.
Top Differences
| Feature | map | flatMap |
|---|---|---|
| Output per input | One-to-one | One-to-many |
| Return type | Stream | Stream |
| Common use | Simple transformation | Flattening collections |
map
- Applies a
functionto each element - Result size = input size
- Does not flatten nested structures
Example
List<String> names = List.of("java", "spring");
List<String> result = names.stream()
.map(String::toUpperCase)
.toList();
// Output: ["JAVA", "SPRING"]
flatMap
- Applies a function that returns a stream
- Flattens multiple streams into one stream
- Used when dealing with collections inside collections
Example
class Employee {
List<String> skills;
}
❌ Wrong (map)
List<List<String>> skills = employees.stream()
.map(Employee::getSkills)
.toList();
✅ Correct (flatMap)
Set<String> skills = employees.stream()
.flatMap(e -> e.getSkills().stream())
.collect(Collectors.toSet());
summary
- Use
mapfor simple transformations - Use
flatMapwhen dealing with nested data
Remember: flattening is the key difference