CodexBloom - Programming Q&A Platform

Java 17: Unexpected NPE When Using Optional with Streams and Collectors

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
java java-17 streams optional Java

Quick question that's been bugging me - I'm relatively new to this, so bear with me. I'm working with a `NullPointerException` when trying to process a list of objects with Java 17's Streams and Collectors. I have a list of `User` objects, and I'm trying to filter them based on an optional field `email`. The goal is to collect non-null emails into a list. Here's the code I'm using: ```java List<User> users = Arrays.asList( new User(1, Optional.of("alice@example.com")), new User(2, Optional.empty()), new User(3, Optional.of("bob@example.com")) ); List<String> emails = users.stream() .map(User::getEmail) .filter(Optional::isPresent) // This line throws NPE .map(Optional::get) .collect(Collectors.toList()); ``` When I run this code, I get a `NullPointerException` on the line where I call `filter(Optional::isPresent)`. I suspect it might be because some of the `User` objects are not instantiated correctly or the `getEmail()` method itself could be problematic. I've tried checking if the users list contains any null values, but it seems fine. Here’s the `User` class I'm using: ```java public class User { private int id; private Optional<String> email; public User(int id, Optional<String> email) { this.id = id; this.email = email; } public Optional<String> getEmail() { return email; } } ``` I also verified that the `email` field is being set correctly in the constructor. Can someone guide to figure out why I'm working with this NPE? Is there a more robust way to handle this when using Streams and Optionals? I'm working with Java in a Docker container on CentOS.