Java Optional Class Methods with Examples

In this tutorial, we will take a look into how to use the Optional class to avoid null checks and NullPointerException. 

Well, the NullPointerException is one of the well-known exceptions that frequently occurs in day-to-day project work right and NullPointerException is like a close friend to the java programmer because whenever we write a program or whenever we work on java project then this null pointer exception will frequently occur all right. 

Video

Java 8 has introduced a new Optional utility class in java.util package. This class can help in avoiding null checks and NullPointerException exceptions.

You can view Optional as a single-value container that either contains a value or doesn't (it is then said to be "empty").

Let's understand some of the frequently or commonly used Java 8 Optional Class methods with examples.

Creating Optional Objects

There are several ways of creating Optional objects.

empty() Method

To create an empty Optional object, we simply need to use its empty() static method:
        Optional<Object> emptyOptional = Optional.empty();

of() Method

The of() static method returns an Optional with the specified present non-null value.

        Optional<String> emailOptional = Optional.of("ramesh@gmail.com");

ofNullable() Method

The ofNullable() static method returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.
        Optional<String> stringOptional = Optional.ofNullable("ramesh@gmail.com");

Here is the complete example with output:

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";

        // of, empty, ofNullable
        Optional<Object> emptyOptional = Optional.empty();
        System.out.println(emptyOptional);

        Optional<String> emailOptional = Optional.of(email);
        System.out.println(emailOptional);

        Optional<String> stringOptional = Optional.ofNullable(email);
        System.out.println(stringOptional);
    }
}

Output:

Optional.empty
Optional[ramesh@gmail.com]
Optional[ramesh@gmail.com]

Get Value from Optional

get() Method

The get() method returns a value if it is present in this Optional otherwise throws NoSuchElementException.

package com.java.lambda.optional;

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String value = stringOptional.get();
        System.out.println(value);
    }
}
Output:
ramesh@gmail.com

Checking Value Presence

isPresent() Method

The isPresent() method returns true if there is a value present, otherwise false.
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        if(stringOptional.isPresent()){
            System.out.println(stringOptional.get());
        }else{
            System.out.println("no value present");
        }
    }
}
Output:
ramesh@gmail.com

Retrieve Default Value

orElse() Method

The orElse() method returns the value if present, otherwise return other (default value).

In the below example, orElse() method return default value because Optional contains null value:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional = stringOptional.orElse("default@gmail.com");
        System.out.println(defaultOptional);
    }
}
Output:
default@gmail.com
In the below example, orElse() method return actual value because Optional contains actual value:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional = stringOptional.orElse("default@gmail.com");
        System.out.println(defaultOptional);
    }
}
Output:
ramesh@gmail.com

orElseGet() Method

The orElseGet() method returns the value if present, otherwise invoke other and return the result of that invocation.

In the below example, orElseGet() method return default value because Optional contains null value:

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
        System.out.println(defaultOptional2);
    }
}
Output:
default@gmail.com
In the below example, orElse() method return actual value because Optional contains actual value:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
        System.out.println(defaultOptional2);
    }
}
Output:
ramesh@gmail.com

Handling Exceptions with Optional

orElseThrow() Method

The orElseThrow() method returns the contained value, if present, otherwise throw an exception to be created by the provided supplier.

In the below example, we pass a null value to the Optional object so orElseThrow() method throws an exception to be created by the provided supplier.

package com.java.lambda.optional;

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String optionalObject = stringOptional.orElseThrow(() -> new IllegalArgumentException("Email is not exist"));
        System.out.println(optionalObject);
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Email is not exist
	at com.java.lambda.optional.OptionalDemo.lambda$main$0(OptionalDemo.java:10)
	at java.base/java.util.Optional.orElseThrow(Optional.java:403)
	at com.java.lambda.optional.OptionalDemo.main(OptionalDemo.java:10)
In the below example, we pass a non-null value to the Optional object so orElseThrow() method returns a value from the Optional object:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String optionalObject = stringOptional.orElseThrow(() -> new IllegalArgumentException("Email is not exist"));
        System.out.println(optionalObject);
    }
}

Output:

ramesh@gmail.com

Optional filter() and map() Methods

filter() Method

If a value is present, and the value matches the given predicate, return an Optional describing the value, otherwise return an empty Optional.
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        // without Optional
        String result = "abc";
        if(result != null && result.contains("abc")){
            System.out.println(result);
        }

        // with Optional
        Optional<String> optionalStr = Optional.of(result);
        optionalStr.filter(res -> res.contains("abc"))
                .ifPresent((res) -> System.out.println(res));
    }
}

Output:

abc
abc

map() Method

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String result = " abc ";
        if(result != null && result.contains("abc")){
            System.out.println(result);
        }

        Optional<String> optionalStr = Optional.of(result);
        optionalStr.filter(res -> res.contains("abc"))
                .map(String::trim)
                .ifPresent((res) -> System.out.println(res));
    }
}


Output:

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments