Describe a scenario where using `flatMap` with streams would be particularly beneficial, and explain how it addresses the problem compared to a nested loop approach.
Java interview question for Advanced practice.
Answer
A common scenario where flatMap shines is processing nested collections. Imagine you have a list of Department objects, and each Department has a list of Employee objects. You want to generate a single list of all employees from all departments who earn over a certain salary. With a traditional nested loop approach, you might do this: java List<Department departments = ...; List<Employee highEarners = new ArrayList<(); for (Department department : departments) { for (Employee employee : department.getEmployees()) { if (employee.getSalary() 100000) { highEarners.add(employee); } } } This is verbose and less expressive. With flatMap, the code becomes more declarative and concise: java List<Employee highEarners = departments.stream() // Stream<Department .flatMap(department - department.getEmployees().stream()) // Stream<Employee .filter(employee - employee.getSalary() 100000) .collect(Collectors.toList()); Here, flatMap takes each Department in the outer stream, gets its list of employees, creates a new stream from that list (department.getEmployees().stream()), and then flattens all these smaller streams into a single, unified Stream<Employee. This elegantly handles the nested iteration, resulting in cleaner, more functional code.
Explanation
The flatMap operation is a powerful tool for flattening nested data structures, often making code more concise and readable compared to nested loops.