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 present
  • flatMap() β†’ Transform when mapper returns another Optional
  • filter() β†’ Keep value only if condition matches
  • orElse() β†’ Return default value if empty
  • orElseGet() β†’ Return computed default if empty
  • orElseThrow() β†’ Throw exception if empty
  • ifPresent() β†’ Run action if value exists

Pro Tip for Teams

When refactoring a large codebase:

  1. Start with utility methods β€” they’re easiest to convert.
  2. Replace deep null chains with map() pipelines.
  3. Return Optional from repository/service methods that may not find a value.
  4. Avoid using Optional for fields or parameters β€” keep it for return types.


← Back to Learning Journey