CodexBloom - Programming Q&A Platform

Unexpected NullPointerException when using Optional in Java 11 Streams

👀 Views: 47 đŸ’Ŧ Answers: 1 📅 Created: 2025-05-31
java optional streams

Quick question that's been bugging me - I'm learning this framework and I'm encountering a `NullPointerException` when processing a list of objects with Java 11 Streams, and I'm not sure why it's happening. My code looks like this: ```java import java.util.List; import java.util.Optional; import java.util.stream.Collectors; class User { private String name; private String email; public User(String name, String email) { this.name = name; this.email = email; } public Optional<String> getEmail() { return Optional.ofNullable(email); } } public class UserProcessor { public List<String> getUserEmails(List<User> users) { return users.stream() .map(User::getEmail) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } } ``` I'm creating a `User` class with an `Optional<String>` return type for the `getEmail` method, but when I call `getUserEmails`, I'm getting a `NullPointerException`. I suspect it might be related to the way I'm handling `Optional` inside the stream, but I'm not sure how to fix it. I've tried checking for null values in the `getEmail` method, but it doesn't seem to help. Here's an example of how I'm calling this method: ```java public class Main { public static void main(String[] args) { List<User> users = List.of( new User("Alice", "alice@example.com"), new User("Bob", null), new User("Charlie", "charlie@example.com") ); UserProcessor processor = new UserProcessor(); List<String> emails = processor.getUserEmails(users); System.out.println(emails); } } ``` When I run this, I get the following stack trace: ``` Exception in thread "main" java.lang.NullPointerException at UserProcessor.getUserEmails(UserProcessor.java:8) at Main.main(Main.java:10) ``` I've checked that `null` values are indeed being passed to the `getEmail()` method as expected, but I'm not sure how to handle these correctly without getting exceptions. Any help or insights on why this `NullPointerException` is occurring would be appreciated! The stack includes Java and several other technologies. This issue appeared after updating to Java latest. Cheers for any assistance!