Java Core: Unexpected NullPointerException when using Optional with Streams
I'm relatively new to this, so bear with me. I'm dealing with After trying multiple solutions online, I still can't figure this out. This might be a silly question, but Quick question that's been bugging me - I'm encountering a `NullPointerException` when trying to filter a stream of objects that contains `Optional` fields... I'm using Java 11 and the scenario is as follows: I have a list of `User` objects, and each `User` has an `Optional<Address>` field. I want to filter users who have a non-null `Address` and then collect their addresses into a list. However, I'm getting a `NullPointerException` at runtime. Here's the relevant code snippet: ```java import java.util.List; import java.util.Optional; import java.util.stream.Collectors; class Address { private String street; // constructors, getters and setters } class User { private Optional<Address> address; // constructors, getters and setters } public class UserAddressCollector { public List<Address> getAddresses(List<User> users) { return users.stream() .flatMap(user -> user.getAddress().stream()) .collect(Collectors.toList()); } } ``` I've ensured that `User` instances in my list are not null, but the `address` field can be empty. When I run the `getAddresses` method, I get the following stack trace: ``` Exception in thread "main" java.lang.NullPointerException at UserAddressCollector.getAddresses(UserAddressCollector.java:10) ... ``` I've also tried adding a filter before the `flatMap`, like this: ```java return users.stream() .filter(user -> user.getAddress() != null) .flatMap(user -> user.getAddress().stream()) .collect(Collectors.toList()); ``` But this does not resolve the issue; I still get the same exception. Can someone explain why this is happening and suggest a proper way to handle this situation? Am I misusing `Optional` or `Streams`? Any best practices on dealing with `Optional` in this context would be appreciated. I'm working on a service that needs to handle this. Any ideas what could be causing this? I'm coming from a different tech stack and learning Java. The stack includes Java and several other technologies. I appreciate any insights! I'm using Java LTS in this project. Thanks for your help in advance!