What is Optional class in java 8 ?

Java 8 added a new class Optional available in java.util package. Java Optional class provides a way to deal with null values. It is used to represent a value is present or not.

A NullpointerException is a common issue in java applications. To prevent this, we normally add frequent NULL checks in our code to check if a variable is not empty before we use it in our program. Optional provides a better approach to handle such situations.Let us explore this by construct with some use cases.

Java Optional class methods :

Modifier and Type Method and Description
static  Optional empty()

Returns an empty Optional instance.

Optional<T> filter(Predicate<? super T> predicate)

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

 Optional flatMap(Function<? super T,Optional> mapper)

If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an emptyOptional.

T get()

If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.

void ifPresent(Consumer<? super T> consumer)

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

boolean isPresent()

Return true if there is a value present, otherwise false.

 Optional map(Function<? super T,? extends U> mapper)

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.

static  Optional of(T value)

Returns an Optional with the specified present non-null value.

static  Optional ofNullable(T value)

Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

T orElse(T other)

Return the value if present, otherwise return other.

T orElseGet(Supplier<? extends T> other)

Return the value if present, otherwise invoke other and return the result of that invocation.

orElseThrow(Supplier<? extends X> exceptionSupplier)

Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

1. empty() :

2. of() :

3. ofNullable() :

4. isPresent() :

5. ifPresent() :

6. filter() :

7. map() :

8. flatMap() :

9. orElse() :

10.  orElseGet() :

11. orElseThrow() :