Avoiding Null Anti Patterns



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
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to
// { autofold
package com.yourself;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class UseOptional {
// }
public List<User> getDatabase() {
return database;
public void setDatabase(List<User> database) {
this.database = database;
public List<User> database = Database.userDatabase.getList();
public Optional<User> getUserFromDatabase(String name) {
//TODO search for the user with the given name in the database, then
//return that user within an Optional if found.
return Optional.empty();
public Optional<String> getUserNameToUpperCaseFromDatabase(String name) {
//TODO search for the user with the given name in the database, then
//return that user's uppercase name within an Optional if found.
return Optional.empty();
//{ autofold
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
Online Participants