Java 11 Stream API - Unexpected Behavior with FlatMap and Optional Handling in Complex Objects
I'm stuck on something that should probably be simple... Quick question that's been bugging me - I'm facing an issue with using the Stream API in Java 11 when attempting to flatten a list of Optional values contained within a complex object structure. I have a class `User` that contains a list of `Address` objects, and each `Address` can optionally have a `PostalCode`. The goal is to obtain a flat list of all `PostalCode`s for a given list of `User`s. However, I'm encountering an unexpected `NoSuchElementException` when trying to retrieve values. My implementation looks like this: ```java import java.util.List; import java.util.Optional; import java.util.stream.Collectors; class User { private List<Address> addresses; public User(List<Address> addresses) { this.addresses = addresses; } public List<Address> getAddresses() { return addresses; } } class Address { private Optional<String> postalCode; public Address(Optional<String> postalCode) { this.postalCode = postalCode; } public Optional<String> getPostalCode() { return postalCode; } } public class Main { public static void main(String[] args) { List<User> users = List.of( new User(List.of(new Address(Optional.of("12345")), new Address(Optional.empty()))), new User(List.of(new Address(Optional.of("67890")), new Address(Optional.of("54321")))) ); List<String> postalCodes = users.stream() .flatMap(user -> user.getAddresses().stream() .flatMap(address -> address.getPostalCode().stream())) .collect(Collectors.toList()); System.out.println(postalCodes); } } ``` When I run this code, it throws a `NoSuchElementException` even though Iβm using `Optional` properly. Iβve tried changing the way I handle the `Optional` to check whether itβs present before extracting the value, but that seems cumbersome and goes against the functional style I'm trying to embrace. Can someone explain what I'm doing wrong or suggest a more elegant solution? Thanks in advance! This is my first time working with Java 3.9.