Creating and Inspecting Optionals
Use Optional.of, ofNullable, empty, isPresent, isEmpty, and get safely.
Creating and Inspecting Optionals
This lesson covers the methods for creating Optional instances and inspecting their contents: isPresent, isEmpty, get, and safe alternatives.
Three Ways to Create an Optional
Create an Optional with Optional.of(), Optional.ofNullable(), or Optional.empty().
import java.util.Optional;
// 1. of: must be non-null
Optional<String> a = Optional.of("hello");
// 2. ofNullable: safely wraps null
String maybeNull = null;
Optional<String> b = Optional.ofNullable(maybeNull); // empty
Optional<String> c = Optional.ofNullable("world"); // present
// 3. empty: explicitly empty
Optional<Integer> empty = Optional.empty();
System.out.println(a.isPresent()); // true
System.out.println(b.isPresent()); // false
System.out.println(c.isEmpty()); // falseAll lessons in this course
- Why Optional Exists
- Creating and Inspecting Optionals
- Transforming Optionals: map and flatMap
- Optional Best Practices