Java 17: implementing Optional and Stream when filtering Null Values
I've encountered a strange issue with I'm optimizing some code but I've looked through the documentation and I'm still confused about I'm having trouble with using `Optional` in conjunction with `Stream` when trying to filter out null values from a list. I have a list of objects, some of which can be null or contain null fields. My goal is to create a method that safely extracts a specific field from these objects without running into `NullPointerExceptions`. Here's a simplified version of my code: ```java import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } } public class Main { public static void main(String[] args) { List<Person> people = Arrays.asList(new Person("Alice"), null, new Person("Bob"), new Person(null)); List<String> names = getNames(people); System.out.println(names); } public static List<String> getNames(List<Person> people) { return people.stream() .map(Optional::ofNullable) .flatMap(Optional::stream) .map(Person::getName) .collect(Collectors.toList()); } } ``` When I run this code, I get the following output: ``` [Alice, null, Bob] ``` I expected to see a list without any null values, but it seems that the `getName()` method is returning null for `Person(null)`. Iβve tried using `filter(Objects::nonNull)` at different points in the stream, but I need to seem to get it to work without losing the valid `Person` objects. Whatβs the best way to achieve this in a more elegant manner without running into null values in the output? Any help would be appreciated! This is part of a larger API I'm building. How would you solve this? Cheers for any assistance! My development environment is macOS. Thanks for your help in advance! I'm working on a CLI tool that needs to handle this. How would you solve this?