Home » Core Java » util » Optional » Java 8 Optional Example

About Dani Buiza

Dani Buiza
Daniel Gutierrez Diez holds a Master in Computer Science Engineering from the University of Oviedo (Spain) and a Post Grade as Specialist in Foreign Trade from the UNED (Spain). Daniel has been working for different clients and companies in several Java projects as programmer, designer, trainer, consultant and technical lead.

Java 8 Optional Example

In this article we are going to show how to use the new java.util.Optional class.

The null reference is a very common problem in Java, everybody got once a NullPointerException because some variable or input parameter was not properly validated. In Java, null, can have a logical value and a meaning; so it is important to take it into consideration and do not ignore it.

With the introduction of java.util.Optional in Java 8, several new possibilities for handling this problematic are available.

The new class is based on the analog functionalities in Haskell and Scala. It contains a value that can be present or not; if the value is not present, the Optional instance is said to be empty.

All examples and code snippets listed have been done using Eclipse Luna version 4.4 and Java version 8 update 5 and can be downloaded at the end of this article.


For the ones that do not know what a NullPointerException is, just try:

		String strNull0 = null;
        System.out.println( strNull0.contains( "something" ) );

The code above would compile but we would get a warning like:

		Null pointer access: The variable strNull can only be null at this location

In order to handle this, we can check and validate for null, or we can surround the block with a try catch. In the following chapters we are going to see how to handle this issue using the new Optional class.


In order to create an Optional we have to indicate what type of value is going to contain:

		Optional emptyOptional = Optional.empty();

The code above shows the creation of an empty optional, that is, its value is null or not initialized. In order to access the value of an optional we can use the method get(); if we try to access the value of the example shown above, we would get the following exception.

            /* empty */
            Optional emptyOptional = Optional.empty();
            System.out.println( emptyOptional.get() );
        catch( NoSuchElementException ex )
            System.out.println( "expected NoSuchElementException" ); //this is executed

The exception thrown is of the type java.util.NoSuchElementException and means that the Optional value is not initialized or null.

In order to create an Optional we can use an existing object and pass it to the Optional using the static method of():

		Optional nonEmptyOptional = Optional.of( str );	

The object passed to the method of() has to be different to null. In case we want to offer the possibility of using potential null values, we can use ofNullable():

		String strNull = null;
		Optional nullableOptional = Optional.ofNullable( strNull );

If we try to pass a null object to an Optional using the method of() we will get a NullPointerException. At the end of this article there is a file to download with examples of all these possible combinations.

Get, orElse, ifElse, orElseThrow…

In order to get the value of an Optional you can use the get() method as shown above. The problem of this method is that you can get a NullPointerException if the value is not initialized. So, although it has some benefits is not solving all our problems.

There are several methods that can be used to retrieve the value of an Optional and handle at the same time the possibility that it is a null reference. We are going to see some of them:


We can use the method orElse():

			Optional optionalCar = Optional.empty();
			price = optionalCar.orElse( defaultCar ).getPrice();

In the code shown above we are trying to access to the price of a Car object, if the Car object is not initialize (or it is null) we will retrieve the price for the default car that we have defined before.


We can indicate the Optional to throw an exception in case its value is null:

			Optional optionalCarNull = Optional.ofNullable( carNull );
			optionalCarNull.orElseThrow( IllegalStateException::new );

In this case, an IllegalStateException will be thrown.


There is the possiblity to check directly if the value is initialized and not null:

			Optional stringToUse = Optional.of( "optional is there" );
			if( stringToUse.isPresent() )
				System.out.println( stringToUse.get() );


And also the option to execute actions directly when the value is present, in combination with Lambdas:

		    Optional stringToUse = Optional.of( "optional is there" );
			stringToUse.ifPresent( System.out::println );

The code shown above and the one before are doing exactly the same. I would prefer to use the second one.

Filtering and mapping in combination with Lambdas

So these are some of the available methods to retrieve the values of an Optional and to handle the null references. Now we are going to see the options that are offered in combination with Lambdas:

Filter (Lambdas)

The Optional class contains a filter() method that expects a Predicate and returns an Optional back if the Predicate is true. Here are some examples:

			// if the value is not present
			Optional carOptionalEmpty = Optional.empty();
			carOptionalEmpty.filter( x -> "250".equals( x.getPrice() ) ).ifPresent( x -> System.out.println( x.getPrice() + " is ok!" ) );

			// if the value does not pass the filter
			Optional carOptionalExpensive = Optional.of( new Car( "3333" ) );
			carOptionalExpensive.filter( x -> "250".equals( x.getPrice() ) ).ifPresent( x -> System.out.println( x.getPrice() + " is ok!" ) );

			// if the value is present and does pass the filter
			Optional carOptionalOk = Optional.of( new Car( "250" ) );
			carOptionalOk.filter( x -> "250".equals( x.getPrice() ) ).ifPresent( x -> System.out.println( x.getPrice() + " is ok!" ) );

As we can see in the snippet above we do not have to take care of the null reference of the value, we can just apply our filters directly and the Optional takes care of all the rest.

Map (Lambdas)

It is also very interesting the method map(). This method “maps” or converts an Optional to another Optional using a Function as parameter. The mapping is only executed, if the result of the past Function is not null. Here are some examples:

			// non empty string map to its length -> we get the lenght as output (18)
			Optional stringOptional = Optional.of( "loooooooong string" );
			Optional sizeOptional = stringOptional.map( String::length ); //map from Optional to Optional
			System.out.println( "size of string " + sizeOptional.orElse( 0 ) );

			// empty string map to its length -> we get 0 as lenght
			Optional stringOptionalNull = Optional.ofNullable( null );
			Optional sizeOptionalNull = stringOptionalNull.map( x -> x.length()  ); // we can use Lambdas as we want
			System.out.println( "size of string " + sizeOptionalNull.orElse( 0 ) );


And that’s it!
In this article we saw several examples about how to use the new Optional class coming out in Java 8. This class allows us to manage null references in a clear and concise way and to handle the famous NullPointerException more effectively. It is interesting to mention that there are also typified “optionals” for the types double, int and long; they work in a similar way than the “generic” one, but their values are the ones of the correspondent type and the operations allowed are the ones related to the primitive type.


For more information about the Optional class and other methods that we did not mention in this article or about Java 8 features in general, please visit:

  • http://docs.oracle.com/javase/8/docs/api/index.html?java/util/Optional.html
  • http://www.javacodegeeks.com/2014/05/java-8-features-tutorial.html
  • Download

    All examples from this article (and some more) can be downloaded in the following link: optionals.zip.
    (No Ratings Yet)
    Start the discussion Views Tweet it!

    Do you want to know how to develop your skillset to become a Java Rockstar?

    Subscribe to our newsletter to start Rocking right now!

    To get you started we give you our best selling eBooks for FREE!


    1. JPA Mini Book

    2. JVM Troubleshooting Guide

    3. JUnit Tutorial for Unit Testing

    4. Java Annotations Tutorial

    5. Java Interview Questions

    6. Spring Interview Questions

    7. Android UI Design


    and many more ....


    Receive Java & Developer job alerts in your Area


    Leave a Reply

    Notify of