Alright π β hereβs your Java Optional βRefactor Mapβ in a one-page visual-style table so you can instantly see how to replace common null patterns with Optional equivalents.
Java Optional Refactor Map
(From old null-check style β to clean Optional style)
Scenario
Old Null-Check Code > Refactored Optional Code
1. Simple null check before action
if (obj != null) { obj.doSomething(); }
β
Optional.ofNullable(obj) .ifPresent(o -> o.doSomething());
2. Null-safe property access
String name = obj != null ? obj.getName() : "Unknown";
β
String name = Optional.ofNullable(obj) .map(MyClass::getName) .orElse("Unknown");
3. Nested null checks
if (order != null && order.getCustomer() != null) {
return order.getCustomer().getEmail();
} return "N/A";
β
return Optional.ofNullable(order) .map(Order::getCustomer) .map(Customer::getEmail) .orElse("N/A");
4. Returning null from method
public String findName() {
return db.findUser() != null ? db.findUser().getName() : null;
}
β
public Optional<String> findName() {
return Optional.ofNullable(db.findUser()) .map(User::getName);
}
5. Default value if null
String city = address != null ? address.getCity() : "Unknown";
β
String city = Optional.ofNullable(address) .map(Address::getCity) .orElse("Unknown");
6. Throw exception if null
if (user == null) throw new IllegalArgumentException();
return user;
β
return Optional.ofNullable(user) .orElseThrow(IllegalArgumentException::new);
7. Transform only if present
Integer len = str != null ? str.length() : null;
β
Optional<Integer> len = Optional.ofNullable(str) .map(String::length);
8. Filter before use
if (user != null && user.getAge() > 18) { ... }
β
Optional.ofNullable(user) .filter(u -> u.getAge() > 18) .ifPresent(...);
Legend
map()β Transform value if presentflatMap()β Transform when mapper returns anotherOptionalfilter()β Keep value only if condition matchesorElse()β Return default value if emptyorElseGet()β Return computed default if emptyorElseThrow()β Throw exception if emptyifPresent()β Run action if value exists
Pro Tip for Teams
When refactoring a large codebase:
- Start with utility methods β theyβre easiest to convert.
- Replace deep null chains with
map()pipelines. - Return
Optionalfrom repository/service methods that may not find a value. - Avoid using
Optionalfor fields or parameters β keep it for return types.