Java
Summary - Optional
Combine ofNullable, map and orElse to write a user finder.
Summary - Optional
In this group you covered the basics of Optional. of wraps a non-null value; ofNullable is null-safe; map and flatMap transform; orElse and orElseGet provide defaults; ifPresent and isPresent enable conditional action.
Chaining these methods produces safe code. First wrap input with ofNullable, then transform with map, finally default with orElse. This pattern removes explicit null checks and leaves readable code behind.
Exercise ofNullable + map + orElse chain
Declare a String input = null. Wrap it with Optional.ofNullable(input), transform with map(String::toUpperCase) and default with orElse("EMPTY"). Print the result with System.out.println.
Show example solution
import java.util.Optional;
public class ChainOptional {
public static void main(String[] args) {
String input = null;
String result = Optional.ofNullable(input)
.map(String::toUpperCase)
.orElse("EMPTY");
System.out.println(result);
}
}
When to use Optional
Optional is primarily a return type; it signals absence of a result. Using it for fields, method parameters or collection elements is discouraged.
Example: Optional<User> findById(int id). This signature tells the caller that the user may not be found. Instead of a null check you use opt.orElseThrow() or opt.ifPresent(...). This makes the code's intent clearer and reduces the risk of NullPointerException.
Exercise isPresent + ifPresent + orElse together
Create an Optional<String> with Optional.of("Sam"). First check with isPresent; if present, print the value prefixed by "Has: " via System.out.println. Then use ifPresent to print with prefix "Welcome ". Finally, print the value obtained from orElse("Guest").
Show example solution
import java.util.Optional;
public class FullOptional {
public static void main(String[] args) {
Optional<String> name = Optional.of("Sam");
if (name.isPresent()) {
System.out.println("Has: " + name.get());
}
name.ifPresent(n -> System.out.println("Welcome " + n));
System.out.println(name.orElse("Guest"));
}
}
Test yourself
-
Which method calls a Supplier when the value is absent?
- orElse
- ifPresent
- isPresent
- orElseGet
Show answer
orElseGet — orElseGet takes a Supplier and calls it only in the empty case.
-
Match each method with its behavior
- ofNullable
- Wraps null safely
- map
- Transforms
- orElse
- Provides a default
- ifPresent
- Runs a Consumer
Next lesson: Function<T,R>