CodexBloom - Programming Q&A Platform

Java 17: NullPointerException When Using Optional in Stream Pipeline with Custom Object Mapping

πŸ‘€ Views: 31 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
java optional stream exception Java

I'm integrating two systems and I'm relatively new to this, so bear with me. I'm encountering a `NullPointerException` when processing a stream of custom objects in Java 17. I have a list of `Person` objects and I'm trying to map them to a `PersonDTO` using an `Optional` to handle potential null values for the name field. Here’s my code snippet: ```java List<Person> people = Arrays.asList( new Person(1, "Alice"), new Person(2, null), new Person(3, "Bob") ); List<PersonDTO> dtos = people.stream() .map(person -> new PersonDTO(person.getId(), Optional.ofNullable(person.getName()).orElse("Unknown"))) .collect(Collectors.toList()); ``` However, when I run this, I get the following stack trace: ``` Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Optional.orElse(Optional.java:408) at my.package.MyClass.lambda$main$0(MyClass.java:26) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513) at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:503) at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:600) at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:264) at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:555) at java.base/java.util.stream.ReferencePipeline.toList(ReferencePipeline.java:612) ``` I’ve already checked if the `Person` class is correctly initializing its fields, and it seems fine. The `getName()` method is correctly returning null for the `Person` instance with ID 2. Is there something wrong with how I'm using `Optional` in the stream? I want to ensure that if the name is null, the DTO gets the default value "Unknown" without throwing an exception. Any insights would be greatly appreciated! I'm working on a service that needs to handle this. What's the best practice here? This issue appeared after updating to Java 3.10.