Java 17: NullPointerException When Using Optional in Custom Stream Collector
I'm maintaining legacy code that I've searched everywhere and can't find a clear answer... I'm working with a `NullPointerException` when trying to use a custom collector in Java 17 that processes a stream of objects containing optional values. My setup involves a list of `Person` objects, and I want to collect their names into a `Map` where the key is the person's ID and the value is their name, but only if the name is present. Hereβs the code snippet Iβve written: ```java import java.util.*; import java.util.stream.*; class Person { private final int id; private final String name; public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public Optional<String> getName() { return Optional.ofNullable(name); } } public class CustomCollectorExample { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person(1, "Alice"), new Person(2, null), new Person(3, "Bob") ); Map<Integer, String> nameMap = people.stream() .collect(Collectors.toMap( Person::getId, person -> person.getName().orElseThrow(() -> new NoSuchElementException("Name not present for ID: " + person.getId())) )); System.out.println(nameMap); } } ``` When I run this code, I get a `NullPointerException` at the line where I'm trying to extract the name. I thought that using `Optional` would prevent me from dealing with null values directly, but it appears that I'm still getting an exception. Iβve tried adding debug statements to print out values right before the collection step, and it shows `null` for the name when `getName()` is called for the second person. What am I missing here? Should I handle the empty optional differently, or is there a better way to collect these names without running into null issues? Any insights would be appreciated! My development environment is macOS. What are your experiences with this?