implementing Filtered Collections and Optional in Java Streams - advanced patterns
I'm working on a project and hit a roadblock. I've encountered a strange issue with Quick question that's been bugging me - I'm working with an scenario while trying to filter a list of objects using Java Streams, specifically when working with `Optional` values... I have a list of `User` objects, each of which has an `Optional<Address>`. My goal is to filter out users who have a non-empty `Address` and then collect their names into a new list. However, I'm getting an unexpected result where users with empty addresses are still included in the final list. Hereβs the relevant code snippet: ```java import java.util.*; import java.util.stream.*; class Address { private String city; public Address(String city) { this.city = city; } public String getCity() { return city; } } class User { private String name; private Optional<Address> address; public User(String name, Address address) { this.name = name; this.address = Optional.of(address); } public User(String name) { this.name = name; this.address = Optional.empty(); } public Optional<Address> getAddress() { return address; } public String getName() { return name; } } public class Main { public static void main(String[] args) { List<User> users = Arrays.asList( new User("Alice", new Address("New York")), new User("Bob"), new User("Charlie", new Address("Los Angeles")) ); List<String> userNamesWithAddress = users.stream() .filter(user -> user.getAddress().isPresent()) .map(User::getName) .collect(Collectors.toList()); System.out.println(userNamesWithAddress); } } ``` When I run this code, I expect to see `"Alice", "Charlie"` in the output. However, the output is `[]`, and I need to seem to figure out why my filtering logic isn't working as expected. I've double-checked that the `User` objects are being created correctly, and I know the addresses are set properly for the users who have them. Is there something I'm missing with how I'm using `Optional` in the filter? I'm currently using Java 11 and would appreciate any insights or suggestions on how to resolve this scenario. Thanks in advance! Is there a better approach? This issue appeared after updating to Java 3.9. I'm using Java stable in this project. I'd really appreciate any guidance on this.