Member-only story
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()…






