Playing With Java Optional

Sofiene Ben Khemis
Aug 17 · 4 min read
Image for post
Image for post
Photo by Kristopher Roller on Unsplash

A container object which may or may not contain a non-null value

Introduction

During your life as a Java developer, you have surely encountered a NullPointerException. Read on if this is the exception you encounter the most. I imagine you might be thinking something like, “Yes, I agree, NullPointerExceptions is a pain for any Java developer, novice or expert, but there’s not much we can do about them.“ This is a common feeling in the programming world. Until Java 8 introduced Optional.

Optional allows an object to wrap those nullable values. The intention is to finally give us the ability to express a type for the returned value more clearly.

Instead of using a Java annotation, which is not checked at compile-time, Optional allows you to boost your methods and indicate that your method probably returns “empty” (and not null) values.

Image for post
Image for post

The NullPointerException problem

Before diving into the usage of Optional, let’s understand what issue it promises to resolve. When we create a java application, we will surely use method chaining to de-reference object properties, which can easily make us fall into the trap of NullPointerException.

String authorZipCode = book.getAuthor().getAddress().getZipCode();

In the above code snippet, there could be a NullPointerException in any get method invocations. Therefore, the Optional class solves this problem by wrapping the object we want and manipulating it.

Importing Optional

First, we start by importing the Optional class located under java.util.

import java.util.Optional;

Creating Optional object

We can build an Optional object by using the empty() method. it will create an empty optional for us.

Output: Optional.empty

But if we want to create Optional objects with values, we can use the of() method which will create an Optional the value passed in parameter.

output: Optional[Hello World]

However, if the value passed in the parameter is null it will throw a NullPointerException. So if the value can be null we have to use the ofNullable(T value) method.

output: Optional.empty
Optional[Hello World]

Checking Value

Once the Optional object is created, the existence of the values ​​inside the Optional object can be checked with the isPresent() method.

output: false
true

Or vice versa, use the isEmpty() method but it is only available from Java 11.

output: true
false

Conditional Action

It is possible to check some conditions and perform some operations on the Optional object with the ifPresent() method. but this is possible only if the Optional object has a value, otherwise, it will do nothing.

output: 11

In Java 9, a method called ifPersentOrElse() has been added to further manipulate conditions if Optional has no value with Runnable action.

output: Other

Return Value

When all values ​​are wrapped with Optional, they can be extracted with the get() method.

output: Hello World

Default Value

If we use the get() method to get the value of the Optional object, but this last has a null as a value, It will not differ from not using the Optional, so to make the difference there is a method called orElse(T other) which gives us the ability to do something else in case of null value.

output: Hello World

Or we could do another thing than just return it by using the orElseGet() method.

output: Hello World

In Java 9, The or() method has been added to perform and return an Optional value for an optional that returns the original value.

output: Optional[Hello World]

For Optional without a value, it will return as the value in the or() statement.

output: Optional[Default]

Exception

If we don’t want to return or do anything after checking that the value is null we can throw an Exception as well.

output: java.lang.IllegalArgumentException

Conditional Return

We can verify the returned value of Optional objects with a method filter() to extract the values ​​we want and remove the unwanted values ​​with a condition.

output: true
false

Transforming Value

You can change the value in the Optional object that contains the value with the map() method.

output: HELLO WORLD

But in case of manipulation of an Optional of Optional, we have to use the flatMap() method.

output: HELLO WORLD

Stream

In Java 9, Optional objects can be converted to Streams and can be operated as Streams.

output: [HELLO WORLD]

Conclusion

In this article, we have introduced most of the important features of the Optional class. It allows developers to avoid redundant null checks by returning values that may or may not be present.

Understanding its usefulness and how to apply it using simple techniques is an important part of mastering modern Java.

The Startup

Medium's largest active publication, followed by +729K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store