NullPointerException when accessing method in List after filtering in Java Streams
I'm relatively new to this, so bear with me. I keep running into I've been struggling with this for a few days now and could really use some help. I'm working with a `NullPointerException` when trying to access a method on an object that I filtered from a `List` using Java Streams. I'm working with Java 11 and using the Stream API to filter a list of user objects, where some of the users may have null names. My goal is to create a new list of user names that are not null, but I keep getting an behavior when I try to access the name. Here's the code snippet I wrote: ```java import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } } public class Main { public static void main(String[] args) { List<User> users = Arrays.asList(new User("Alice"), new User(null), new User("Bob")); List<String> userNames = users.stream() .filter(user -> user.getName() != null) .map(User::getName) .collect(Collectors.toList()); System.out.println(userNames); } } ``` When I run this code, I get the following behavior: ``` Exception in thread "main" java.lang.NullPointerException at User.getName(Main.java:9) at Main.lambda$main$0(Main.java:16) at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ... ``` I thought the filter would prevent the `getName()` method from being called on a null user, but it seems that the method is still being invoked on the user object that is `null`. I also tried using `filter(Objects::nonNull)` before accessing `getName()`, but that didn't work as expected either. Can anyone explain why I'm working with this scenario and how I can resolve it while ensuring that I only collect non-null names into my list? The project is a mobile app built with Java. Is this even possible? Thanks for your help in advance! Is there a simpler solution I'm overlooking? For context: I'm using Java on Windows 10. Am I missing something obvious?