Video in progress

Strong Middle 🌊 Streams and lambdas

What happens if the function passed to Optional.map() returns null? And with flatMap?

If the result is null, map doesn't fail: it returns an empty Optional. That is why you can safely walk a chain of getters that return null. The function passed to flatMap, though, must return an Optional; if it returns null, you get an NPE.

📖 Answer

record Address(String city) {}
record Customer(Address address) {}   // address can be null

String city = Optional.ofNullable(customer)
        .map(Customer::address)       // null -> Optional.empty()
        .map(Address::city)           // this step doesn't run
        .orElse("noma'lum");

Inside map, it does Optional.ofNullable(mapper.apply(value)), so null automatically becomes "empty". This is very convenient for wrapping old APIs that return null.

flatMap has a different contract: the function gives an Optional, and if the Optional itself is null, you get a NullPointerException:

Optional<Address> findAddress(Customer c) {
    if (c.address() == null) return null;   // a mistake! it should be Optional.empty()
    return Optional.of(c.address());
}

Optional.of(customer).flatMap(this::findAddress);   // NPE

The second subtle point: since map treats "null = absent", you can't tell apart "there is a value, but it is null". For example, Map.get(key) gives null both when the key is missing and when the value is null; Optional.ofNullable(map.get(key)) treats them the same. If you need the difference, use containsKey.

And one more: in Optional.of(x).map(...), if x itself is null, the error comes from of and never reaches map. If the input is nullable, start the chain with ofNullable.