Unexpected NullPointerException in Java 11 with Optional and Custom Object Mapping
I've been banging my head against this for hours. I've been struggling with this for a few days now and could really use some help. I'm encountering a `NullPointerException` when trying to map a custom object to a DTO using `Optional` in Java 11. My code attempts to retrieve a value from an `Optional` and if it's not present, I want to return a default object. However, I'm getting an unexpected `NullPointerException` that I can't seem to trace back to any specific line. Here's the relevant code snippet: ```java import java.util.Optional; class User { private String name; // Constructor, getters, and setters } class UserDTO { private String displayName; // Constructor, getters, and setters } public class UserMapper { public UserDTO mapToDTO(Optional<User> userOptional) { return userOptional.map(user -> new UserDTO(user.getName())) .orElseGet(() -> new UserDTO("Default User")); } } ``` The `User` object is sometimes null in my database (which is fine), and the mapping logic is supposed to handle that gracefully. However, I'm seeing this stack trace in my logs: ``` java.lang.NullPointerException at UserMapper.mapToDTO(UserMapper.java:10) at MyService.processUser(MyService.java:25) ``` Upon investigation, I found that the issue arises when the `User` object is null, leading to an exception when trying to call `user.getName()`. I've confirmed that the `Optional<User>` is being populated correctly in the service layer. I tried adding null checks before accessing any properties of the `User` object, but it feels like I'm missing something fundamental about using `Optional`. How can I properly handle this scenario without running into `NullPointerException`? Any insights or best practices would be greatly appreciated! I'm working on a CLI tool that needs to handle this. Any help would be greatly appreciated!