Back
Close

Avoiding Null Anti Patterns

[CG]jupoulton
5,826 views

Optional

Java 8 includes a nifty new class which was made specifically to manage missing values. It is a wrapper class which contains either an instance of the given class or a null value. Therefore, it is possible to manipulate null values as if they were normal instances without necessarily having to perform a null check at every step.

If you're versed in Functional Programming, you may have guessed that Optional is the Java implementation of a maybe monad.

You can check if the Optional contains a value with the isPresent() method.

An instance of Optional can be created from a potentially null object with the ofNullable(value) method.

How is this helpful? Now, by using the map() method, you can perform an operation on your Optional object without needing to check if a value exists first.

Don't hesitate to check out Optional in the javadoc.

Try to solve the two exercises below:

Solve the first TODO
Solve the second TODO

Tip: the Stream API works very well with Optionals 😉

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
// {...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants