7 Practical Java Tips You Should Know

Do’s and don’ts of Java Optional

Milos Zivkovic
Javarevisited

--

Photo by ThisIsEngineering from Pexels

Optional prevents null pointer exceptions. Even so, Optional can be abused, overused, and downgrade your code quality.

Trying workarounds for ifNotPresent? Using map when flatMap can be used? You’re getting some weird behavior with orElse? How to avoid an empty catch with an Optional?

We answer all of the above. Let’s dive in.

How to execute an action if the value is absent?

Let’s say you want to handle Optional when value is not present. You want to print the value if present. Print something else if the value is not present.

What you don’t want to do:

Why you don’t want this approach? This approach returns the value. Either way. Won’t work for our case, since we need to print a message. Actions we want to do are printing of the value, and here we return the value.

--

--