1. Scenario: Employee Filtering
Q: You have a list of Employee objects. How would you filter employees who have a salary > 50,000 and live in "New York", using Java 8?
✅ Answer:
List<Employee> filtered = employees.stream()
.filter(e -> e.getSalary() > 50000 && "New York".equals(e.getCity()))
.collect(Collectors.toList());
2. Scenario: Grouping Data
Q: How do you group a list of employees by their department using Java 8?
✅ Answer:
Map<String, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
3. Scenario: Find Highest Paid Employee
Q: How to find the employee with the highest salary from a list?
✅ Answer:
Optional<Employee> highestPaid = employees.stream()
.max(Comparator.comparing(Employee::getSalary));
4. Scenario: Flatting Nested Collections
Q: You have a List<List<String>>. How do you flatten it to a single List<String>?
✅ Answer:
List<String> flatList = listOfLists.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
5. Scenario: Using Optional
Q: How would you safely retrieve the city of an employee without getting NullPointerException?
✅ Answer:
Optional<Employee> emp = Optional.ofNullable(employee);
String city = emp.map(Employee::getAddress)
.map(Address::getCity)
.orElse("Unknown");