Command Palette

Search for a command to run...

Back to the lesson: Topic 10.7 — Optional
Core Java · Example 3 of 4 Java 16+

map, flatMap and filter instead of nested null checks

Optional<T> is a box that holds either one value or nothing, used as a method's return type to say "there may be no result". Instead of returning null and hoping the caller checks, you return an Optional and the caller must decide what happens when it's empty, with orElse, orElseThrow, map and friends.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static Optional<Integer> parseAge(String s) that returns empty for non-numbers and for ages outside 0..150. Print the result for "42", "abc" and "200", using orElse(-1).

02

Given Map<String, String> managers (employee to manager), write a method that returns the manager's manager as Optional<String>, using ofNullable and map. Test it on a three-level chain and on someone at the top.

03

From List.of("7", "x", "12", "", "5"), use your parseAge and flatMap(Optional::stream) to print the sum of the valid ages.

Explain it without notes

01

Why was Optional added, and what is it meant to be used for?

02

What's the difference between orElse and orElseGet?

03

When do you use map and when flatMap on an Optional?

04

Where should you not use Optional, and why?

map, flatMap and filter instead of nested null checks Java 16+
Sign in to run this example in your browser.

Expected output

PUNE | PUNE
UNKNOWN | UNKNOWN
UNKNOWN | UNKNOWN
UNKNOWN | UNKNOWN
pin starts with 41: true
pin starts with 56: false
map instead of flatMap: Optional[Optional[Address[city=Pune, pin=411001]]]