Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite using Optional without get():

Java
User u = repo.findById(id);
if (u != null && u.getAddress() != null) {
return u.getAddress().getCity();
}
return "unknown";

where findById now returns Optional<User>.

The rewrite is one expression: return repo.findById(id).map(User::getAddress).map(Address::getCity).orElse("unknown"). It works because map returns an empty Optional when its function returns null, so a missing user and a null address both fall through to the default; if a getter already returned Optional, we would use flatMap instead. orElse is fine here because the default is a constant.

Why this question is asked

Null-check chains like the one in this question appear in almost every codebase that predates Optional, and repository methods such as Spring Data's findById now return Optional, so this rewrite is something we do in real code all the time. Interviewers ask it to see whether we can use map and flatMap fluently, without falling back to isPresent and get, and whether we notice the small behavioural differences a rewrite can introduce. In this answer, we will recap what the original code does, build the Optional version step by step, see why null addresses are handled for free, look at flatMap for Optional-returning getters, and check that the behaviour matches.

1A Quick Recap of the Original Code

Here is the original, before findById returned Optional.

Java
User u = repo.findById(id);
if (u != null && u.getAddress() != null) {
return u.getAddress().getCity();
}
return "unknown";

It handles two cases of absence: the user does not exist, and the user exists but has no address. In both, it returns "unknown". Notice that it calls getAddress() twice, and that if the address exists but its city is null, it returns null. Keep that last detail in mind; we will come back to it.

Now findById returns Optional<User>. The tempting quick fix is to call get() or check isPresent(), but that just rewrites the null check with more ceremony. Optional's map is the tool designed for this.

2Building the Chain Step by Step

map(function) applies the function to the value if one is present and wraps the result in a new Optional. If the Optional is empty, map does nothing and returns an empty Optional. So we can describe the path from user to city as a series of maps, and the absence of any link is handled automatically.

Java
String city = repo.findById(id) // Optional<User>
.map(User::getAddress) // Optional<Address>: empty if no user or no address
.map(Address::getCity) // Optional<String>: empty if any earlier step was empty
.orElse("unknown"); // the String, or "unknown"
return city;
Step throughHow the chain handles each case
  1. findById(id)Optional<User>
  2. Is there a user?
    Yesmap(User::getAddress)Noempty, skip to orElse
  3. Did getAddress() return non-null?
    Yesmap(Address::getCity)Noempty, skip to orElse
  4. Did getCity() return non-null?
    Yesreturn the cityNoempty, skip to orElse
  5. orElse("unknown")used for every empty case

5 steps in order. Play them, or step through them one at a time.

Every missing link short-circuits to the same default.

Read it as a sentence: find the user, take their address, take its city, or else unknown. Each step only runs if the previous one produced a value. getAddress() is now called once, there are no temporary variables, and there is no way to reach getCity() on a missing address.

3Why a Null Address Is Handled for Free

The key fact is in map's contract: if the function returns null, map returns an empty Optional rather than an Optional holding null (which cannot exist). Internally map calls Optional.ofNullable on the result. So when getAddress() returns null, the next map sees an empty Optional and skips Address::getCity.

Java
Optional<User> withoutAddress = Optional.of(new User("ana", null));
System.out.println(withoutAddress.map(User::getAddress)); // Optional.empty
System.out.println(withoutAddress.map(User::getAddress)
.map(Address::getCity).orElse("unknown")); // unknown
Optional<User> missing = Optional.empty();
System.out.println(missing.map(User::getAddress).map(Address::getCity)
.orElse("unknown")); // unknown
Optional<User> full = Optional.of(new User("ben", new Address("Lyon")));
System.out.println(full.map(User::getAddress).map(Address::getCity)
.orElse("unknown")); // Lyon

This is why map chains are the idiomatic replacement for nested null checks: legacy getters that return null fit straight into them.

4When a Getter Already Returns Optional: flatMap

Suppose the User class is modernised and getAddress() now returns Optional<Address>. Using map would wrap that Optional in another Optional.

Java
// map with an Optional-returning getter gives a nested Optional
Optional<Optional<Address>> nested = repo.findById(id).map(User::getAddress);
// flatMap uses the getter's Optional directly instead of wrapping it
String city = repo.findById(id)
.flatMap(User::getAddress) // Optional<Address>
.map(Address::getCity) // getCity still returns a plain String
.orElse("unknown");

The rule is easy to remember: use map when the function returns a plain value, which may be null, and flatMap when it returns an Optional. flatMap requires its function to return a non-null Optional; returning null from it throws a NullPointerException.

5Checking That the Behaviour Matches

A rewrite should keep behaviour the same unless we decide otherwise. Comparing the cases shows one difference.

Old and new behaviour
CaseOriginal codeOptional chain
No user with this id"unknown""unknown"
User without address"unknown""unknown"
Address with city "Lyon""Lyon""Lyon"
Address with null citynull"unknown"
The only difference is an improvement, but it should be a deliberate one, with a test.

For a missing user, a null address and a full address, the old and new versions agree. For an address whose city is null, the old code returned null, while the new code returns "unknown", because map(Address::getCity) produces an empty Optional. In most systems this is an improvement, since callers were probably not expecting null, but it is still a change, so we should check the callers or confirm with whoever owns the behaviour, and add a test for that case so the decision is recorded.

Finally, orElse is the right fallback here because "unknown" is a constant. orElse evaluates its argument even when a value is present, which costs nothing for a string literal. If the default needed computing, for example a lookup of the user's region, we would switch to orElseGet with a lambda so it only runs when needed.

6Follow-up questions

Why not just write if (opt.isPresent()) return opt.get()...?

Because it is the original null check with extra steps. It still needs separate handling for the null address, and it makes it easy to call get() without the check in a later edit. The map chain handles every missing link in one expression and cannot throw.

Is creating several Optional objects in the chain expensive?

Each map may allocate a small Optional, but this is negligible next to a repository call, and the JIT often removes such short-lived allocations. In the rare hot loop where it matters, a plain null check is acceptable, but for service code readability wins.

What if the city should be reported as missing rather than defaulted?

Then return the Optional<String> itself, ending the chain after the last map, and let the caller decide. Or, if absence is an error, end with orElseThrow and a domain exception. The choice depends on what the caller needs to know.

7Conclusion

In this answer, we rewrote a nested null check as repo.findById(id).map(User::getAddress).map(Address::getCity).orElse("unknown"). map applies a function only when a value is present and turns a null result into an empty Optional, so a missing user and a null address both reach the default without explicit checks. We used flatMap when a getter already returns Optional, kept orElse because the default is a constant, and noticed that a null city now gives "unknown" instead of null, a deliberate improvement worth a test.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write it as one chain: return repo.findById(id).map(User::getAddress).map(Address::getCity).orElse("unknown"). findById gives an Optional<User>. map(User::getAddress) applies the getter only if a user is present, and the important detail is that if the getter returns null, map gives back an empty Optional, because it wraps the result with ofNullable.

Then, if they want more

So both the missing user and the null address cases become empty without any explicit check. The second map does the same for the city, and orElse supplies "unknown" for any empty case. orElse is fine here because the default is a constant; if the default were expensive to compute, I would use orElseGet with a lambda.

If the User class later changed getAddress to return Optional<Address>, I would switch that step to flatMap, because map would give me an Optional of an Optional. I would also point out one behavioural difference: the original code returned null when the address existed but the city was null, and the new version returns "unknown".

That is probably better for callers, but it is a change, so I would check with the callers and add a test for it. And I would avoid isPresent and get, which just rewrite the null check with more ceremony.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Rewrite using Optional without get():": https://scrivio-interview-library.netlify.app/java/optional/2a45249c09/