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:

		String text = ...;
		if (text != null) {

We can use Optionnal ifPresent() method alternatively:

String text = ...;
Optional opText= Optional.ofNullable(text);
opText.ifPresent(s -> System.out.println(s));
2. Create an Optional object

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

Optional opText = Optional.empty();

– not-null value Optional:

String text = "not-null value";
Optional opText = Optional.of(text);

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

String text = null;
Optional opText = Optional.ofNullable(text);
II. Usage
1. if value is present, do something
		String text = "Java Sample Approach";
		Optional opText2 = Optional.ofNullable(text);
		opText2.ifPresent(s -> System.out.println("this is NOT null value: " + s));
		// this is NOT null value: Java Sample Approach
2. if value is null
String text = null;
Optional opText1 = Optional.ofNullable(text);

– throw an exception:

// Exception in thread "main" java.lang.IllegalStateException
// 	at java.util.Optional.orElseThrow(

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

System.out.println(opText1.orElse("this is a null String"));
// this is a null String
3. check property of an object

We have a class Address with field location:

public class Address {
	private String location;

	public Address() {

	public Address(String location) {
		this.location = location;

	public String getLocation() {
		return location;

	public void setLocation(String location) {
		this.location = 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:

		Address address = new Address("USA");
opAddress = Optional.ofNullable(address); -> location.contains("US")) .ifPresent(s -> System.out.println("Address contains \"US\": " + s)); // Address contains "US": USA
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():

		Address address1 = null;
opAddress1 = Optional.ofNullable(address1); Address address2 = opAddress1.orElseGet(() -> { System.out.println("System: address with null location will be replace with default value"); return new Address("default location for null Address");}); System.out.println(address2.getLocation()); // System: address with null location will be replace with default value // Location: default location for null Address
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:

Customer customer = new Customer("Jack");
String location = customer.getAddress().getLocation();

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

public class Customer {
	private String name;
	private Optional
address = Optional.empty(); public Customer(String name) { = name; } public String getName() { return name; } public void setName(String name) { = name; } public Optional
getAddress() { return address; } public void setAddress(Optional
address) { this.address = address; } }

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

		Customer customer = new Customer("Jack");
		// customer.setAddress(Optional.of(new Address("US")));

		Optional opCustomer = Optional.ofNullable(customer);

		String location = opCustomer.flatMap(Customer::getAddress).map(Address::getLocation)
				.orElse("location not detected");

		// location not detected
III. Source code


By grokonez | December 20, 2016.

Last updated on September 29, 2017.

Related Posts

Got Something To Say:

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