Java 8 Optional

Null reference causes many problems because it often denotes the absence of a value. Java 8 Optional is a new class that can help us handle these cases instead of checking null.

I. Concept
1. Alternative way to check Null

Instead of having to make a null check before doing something:

We can use Optionnal ifPresent() method alternatively:

2. Create an Optional object

We have some ways to create an Optional object:
– empty Optional:

– not-null value Optional:

If text is null, a NullPointerException will be thrown immediately.
Optional object can hold a null value:

II. Usage
1. if value is present, do something

2. if value is null

– throw an exception:

– or replace with a default value using orElse() method:

3. check property of an object

We have a class Address with field location:

We also have an instance of the Address class.
To make sure that the location field inside is not null. contains “US“, print a String if it is true, we use filter() and ifPresent() method:

4. return a default object

We also can return the value of object if present, otherwise, invoke some codes and return a default object using orElseGet():

5. Optional as a field

Assume that we have Customer class that has Address as a field, and we wanna make this code in safe way:

To work with null Address field inside, we make that field Optional:
private Optional<Address> address = Optional.empty();

Now, this is how we return location safety and replace with a default value using flatmap() and map() method:

III. Source code


Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *