Difference between map() and flatMap() with a real-world example.
Java 8 Interview Question and Answer
Difference between map() and flatMap() with a real-world example.
Java 8 Interview Question and Answer
Both map() and flatMap() are intermediate operations in the Java Stream API used to transform data, but they differ in how they handle nested structures.
map() is used for one-to-one transformation. It takes one input element and transforms it into exactly one output element. If the mapping function itself returns a collection, the result will be a stream of collections.
flatMap() is used for one-to-many transformation. It not only maps elements but also flattens nested structures into a single stream. This is especially useful when dealing with collections inside collections.
In short, map() transforms data, while flatMap() transforms and flattens data.
Real-World Example : An organization has employees, and each employee has multiple skills. We want to extract all skills.
Employee Class
class Employee {
private String name;
private List<String> skills;
public Employee(String name, List<String> skills) {
this.name = name;
this.skills = skills;
}
public List<String> getSkills() {
return skills;
}
}
Using map() (Nested Result)
List<Employee> employees = List.of(
new Employee("Vinoth", List.of("Java", "Spring")),
new Employee("Kumar", List.of("Docker", "AWS"))
);
employees.stream()
.map(Employee::getSkills)
.forEach(System.out::println);
Output
[Java, Spring]
[Docker, AWS]
Here, map() converts each employee into a list of skills, resulting in a stream of lists.
Using flatMap() (Flattened Result)
employees.stream()
.flatMap(emp -> emp.getSkills().stream())
.forEach(System.out::println);
Output
Java
Spring
Docker
AWS
Here, flatMap() first maps each employee to a stream of skills and then flattens them into a single stream
*map()produces one output per input, while `flatMap()`* produces multiple outputs per input and flattens the result
When to Use Which?
- Use map() when the output is one-to-one
- Use flatMap() when dealing with nested collections
메타데이터
- post_id
- d6216a81822e
- slug
- difference-between-map-and-flatmap-with-a-real-world-example-d6216a81822e
- url
- https://medium.com/@vino7tech/difference-between-map-and-flatmap-with-a-real-world-example-d6216a81822e
- canonical_url
- https://medium.com/@vino7tech/difference-between-map-and-flatmap-with-a-real-world-example-d6216a81822e
- author_url
- https://medium.com/@vino7tech
- status
- ok
- fetched_at
- 2026-07-17 00:53:25