Java Optional Best Practices


map vs flatMap

  • Use flatMap when the transformation function returns an Optional: flatMap flattens it and returns Optional instead of Optional<Optional>.

Filter out Optional.empty() from a stream of Optional

Can be simplified as:

Call chains of nullable API

orElse, orElseGet, orElseThrow

  • If possible, don’t use Optional.isPresent(),

When to (not) use Optional in API?

  • Optionals force the user of an API to confront the fact that there may be no value returned.
    • Throwing an unchecked exception or returning a null allows the user to ignore this eventuality.
    • throwing a checked exception requires additional boilerplate code in the client
  • (Only) Use Optional as a return type
  • Return Optional.empty() in error case, or throw exception?
  • Don’t use Optional as parameter for public methods or constructors
    • for optional(nullable) parameters, or boolean parameter, use distinct (or overloaded) methods
    • We can still use Optinonal in private implementation.
  • Don’t use Optional as instance variable; Don’t use Optional within the private scope.
    • Use @Nullable annotation.
  • Don’t use Optional to return collection or arrays: use empty collection/arrays instead

Other Tips about Optional

  • Never assign null to an optional.
  • Make sure an optional has a value before calling get().
    • or use ifPresent, orElse, orElseGet
  • Optional is not Serializable
  • Be careful of the difference between Optional.of() and Optional.ofNullable()
  • Use java.util.OptionalInt/Long/Double, never return an optional of a boxed primitive type.

Methods of Optional

  • ifPresent, filter, map, flatMap

New methods after Java 8

  • Use stream() method on Optional instance to treat Optional instance as a Stream
    • Use .flatMap(Optional::stream) instead of .filter(Optional::isPresent).map(Optional::get)
  • .or(Supplier<? extends Optional<? extends T>> supplier)
  • .ifPresentOrElse(action, emptyAction)
  • Optional.isEmpty()

When work with legacy code

  • com.google.common.base.Optional.toJavaUtil/fromJavaUtil

Example of Using Optinonal

Can be simplified as:

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)