Strange NullPointerException when using Optional in Spring Boot Service with Java 17
I'm working with a persistent `NullPointerException` when trying to use `Optional` in my Spring Boot service. The behavior occurs intermittently, particularly when I try to access a nested property of an object that I expect to be present. Here's a snippet of my service method: ```java public UserDto getUserById(Long userId) { return userRepository.findById(userId) .map(user -> { return new UserDto(user.getId(), user.getName(), user.getAddress().getStreet()); }) .orElseThrow(() -> new UserNotFoundException("User not found")); } ``` The `User` entity has a `Address` field, and I'm getting a `NullPointerException` on `user.getAddress().getStreet()` even when `findById` returns an `Optional<User>` that is present. I've verified that the `Address` field can be `null` in certain scenarios. I thought using `Optional` would help handle this situation, but it seems like I'm still running into trouble. I've tried wrapping the access to the address in another `Optional` like this: ```java public UserDto getUserById(Long userId) { return userRepository.findById(userId) .map(user -> { String street = Optional.ofNullable(user.getAddress()) .map(Address::getStreet) .orElse("No street provided"); return new UserDto(user.getId(), user.getName(), street); }) .orElseThrow(() -> new UserNotFoundException("User not found")); } ``` However, I'm still seeing the same scenario at times. The stack trace points to the `getStreet()` method in the `Address` class, and I'm confused about how this could happen when I thought I was being cautious with `Optional`. Is there a better way to ensure that I'm not dereferencing a `null` object? Any advice on best practices for working with `Optional` in this context? I'm using Spring Boot version 2.6.3 and Java 17.