CodexBloom - Programming Q&A Platform

Intermittent NullPointerException when using Optional in Java 17 with Streams

👀 Views: 295 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
java streams optional exception-handling Java

I'm optimizing some code but I need some guidance on I'm trying to configure I'm working on a personal project and I'm working with an intermittent `NullPointerException` in my Java 17 application while working with `Optional` and Java Streams... The code block below is part of a service method that processes a list of user objects and tries to extract their email addresses. If the user is present, I want to collect their emails into a list, but occasionally I see a `NullPointerException` when calling `.get()` on the `Optional`. Here's the relevant code: ```java import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class UserService { public List<String> getActiveUserEmails(List<User> users) { return users.stream() .map(this::getEmail) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } private Optional<String> getEmail(User user) { return Optional.ofNullable(user) .map(User::getEmail); } } ``` The `User` class looks something like this: ```java public class User { private String email; public String getEmail() { return email; } // Other fields and methods } ``` The scenario seems to arise when the `users` list contains a `null` entry, which I handle via `Optional.ofNullable(user)`. However, I still get a `NullPointerException` at the `.get()` call. I suspected that maybe users can have an `email` field set to `null`, and in those cases, I should not be adding them to the result list. I've tried to use `flatMap` instead of `map`, but that doesn't seem to fix the scenario either. I tried adding additional checks, but the question continues intermittently. The stack trace shows that it's happening in the line where I call `Optional::get`. Can someone help identify what might be going wrong here? Am I misusing `Optional` in this context? I'm working on a service that needs to handle this. Has anyone else encountered this? I'm working in a CentOS environment. Thanks for your help in advance! This is for a desktop app running on Debian. I'd be grateful for any help. I appreciate any insights!