πΉ What is Optional?
Optional<T>
is a container object that may or may not hold a non-null value.
β Itβs a wrapper around an object that helps you write null-safe code.
π§± Why Use Optional
?
Before Java 8:
With Optional
:
π¦ How to Create Optional
Method | Description |
---|---|
Optional.of(value) |
Creates an Optional with a non-null value (throws NPE if null) |
Optional.ofNullable(value) |
Accepts null; returns empty if null |
Optional.empty() |
Creates an empty Optional |
Optional<String> name = Optional.of("Aftab");
Optional<String> empty = Optional.empty();
Optional<String> maybeName = Optional.ofNullable(null);
β Common Methods in Optional
Method | Description |
---|---|
isPresent() |
Returns true if value is present |
ifPresent(Consumer) |
Runs code if value is present |
get() |
Returns value (avoid if unsure β may throw) |
orElse(T) |
Returns value or default if absent |
orElseGet(Supplier) |
Lazy version of orElse()
|
orElseThrow() |
Throws exception if value is absent |
map(Function) |
Transforms the value inside the Optional |
flatMap(Function) |
Like map, but avoids nested Optionals |
filter(Predicate) |
Filters value with condition |
π‘ Examples
1. Avoiding Null Checks
2. Using orElse
/ orElseGet
3. Using map
to Transform
π§ When to Use Optional
β Use in:
- Return types of methods
- Wrapping potentially-null results (e.g., from DB or API)
- Stream operations
π« Don't use in:
- Fields in entity classes (avoid for serialization)
- Method parameters (not a good practice)
β Summary
Attribute | Value |
---|---|
Package | java.util.Optional |
Purpose | Null-safety, expressive API |
Replaces | Manual null checks |
Key Benefit | Avoid NullPointerException
|