Java 17: NPE When Using Optional with Streams and Custom Objects
I'm dealing with I'm encountering a NullPointerException when trying to use an Optional in conjunction with Java Streams on a list of custom objects. I have a class called `Employee` that has a `getDepartment()` method returning an `Optional<Department>`. When I run the following code, I receive an NPE if some employees do not have a department set. Here's the relevant code snippet: ```java import java.util.List; import java.util.Optional; import java.util.stream.Collectors; class Department { private String name; // Constructor, getters, and setters } class Employee { private String name; private Optional<Department> department; public Employee(String name, Department department) { this.name = name; this.department = Optional.ofNullable(department); } public Optional<Department> getDepartment() { return department; } } public class Main { public static void main(String[] args) { List<Employee> employees = List.of( new Employee("Alice", new Department("HR")), new Employee("Bob", null), new Employee("Charlie", new Department("IT")) ); List<String> departments = employees.stream() .map(Employee::getDepartment) .map(Optional::get) // NPE occurs here .map(Department::getName) .collect(Collectors.toList()); System.out.println(departments); } } ``` When I execute this code, it throws an `java.lang.NullPointerException` at the line `map(Optional::get)`, which I suspect is due to trying to access the `get()` method on an empty Optional. I thought that using `Optional` would prevent NPEs, so I'm not sure what Iām missing here. I've tried using `filter()` before mapping, but that doesn't seem to resolve the issue. How can I handle this scenario properly, so I don't run into NPEs when some employees don't have a department? Thanks, I really appreciate it!