Optional class in Java
Last Updated : 17 Mar 2025
Java introduced a new class Optional in JDK 8 version. It is a public final class and used to deal with NullPointerException in Java application. We must import java.util package to use this class. It provides methods that are used to check the presence of value for particular variable.
Java Optional Class Methods
| Methods | Description |
|---|---|
| public static <T> Optional<T> empty() | It returns an empty Optional object. No value is present for this Optional. |
| public static <T> Optional<T> of(T value) | It returns an Optional with the specified present non-null value. |
| public static <T> Optional<T> ofNullable(T value) | It returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. |
| public T get() | If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException. |
| public boolean isPresent() | It returns true if there is a value present, otherwise false. |
| public void ifPresent(Consumer<? super T> consumer) | If a value is present, invoke the specified consumer with the value, otherwise do nothing. |
| public 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. |
| public <U> Optional<U> 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. Otherwise return an empty Optional. |
| public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper) | If a value is present, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional. |
| public T orElse(T other) | It returns the value if present, otherwise returns other. |
| public T orElseGet(Supplier<? extends T> other) | It returns the value if present, otherwise invoke other and return the result of that invocation. |
| public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable | It returns the contained value, if present, otherwise throw an exception to be created by the provided supplier. |
| public boolean equals(Object obj) | Indicates whether some other object is "equal to" this Optional or not. The other object is considered equal if:
|
| public int hashCode() | It returns the hash code value of the present value, if any, or returns 0 (zero) if no value is present. |
| public String toString() | It returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions. |
Example: Java Program Without Using Optional
In the following example, we are not using Optional class. The program terminates abnormally and throws a NullPointerException.
File Name: OptionalExample.java
Output:
Exception in thread "main" java.lang.NullPointerException at lambdaExample.OptionalExample.main(OptionalExample.java:6)
To avoid the abnormal termination, we use Optional class. In the following example, we are using Optional. So, our program can execute without crashing.
Java Optional Example: If Value is not Present
File Name: OptionalExample.java
Output:
string value is not present
Java Optional Example: If Value is Present
File Name: OptionalExample.java
Output:
java optional class example
Another Java Optional Example
Output:
JAVA OPTIONAL CLASS EXAMPLE JAVA OPTIONAL CLASS EXAMPLE java optional class example
Java Optional Methods Example
File Name: OptionalExample.java
Output:
Optional.empty Filtered value: Optional.empty Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE] Getting value: JAVA OPTIONAL CLASS EXAMPLE Getting hashCode: -619947648 Is value present: true Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE] orElse: JAVA OPTIONAL CLASS EXAMPLE orElse: Value is not present JAVA OPTIONAL CLASS EXAMPLE
Using Alternate Values if Value is not Present: orElse() and orElseGet()
The methods orElse() and orElseGet() in Java's Optional class are used to retrieve a value from an Optional object when the contained value is not present. Both serve similar purposes but differ slightly in how they operate. Let's see the usages of these two methods through a Java program.
File Name: OptionalOrElseExample.java
Output:
Name with orElse: Default User Computing default username... Name with orElseGet: Computed Default User
Optional Value Transformation With map() and flatMap()
Using map() Method
The map() method applies a function to the value inside the Optional if it is present. It then wraps the result in a new Optional. This is useful for transforming the value while still keeping it within an Optional container.
File Name: OptionalFilterExample.java
Output:
JOHN DOE
Using flatMap() Method
The flatMap() method applies a function to the value inside the Optional, and the function must return an Optional. This is useful when you want to avoid nested Optional (i.e., Optional<Optional<T>>) structures and instead get a flat structure of Optional<T>.
File Name: OptionalFlatMapExample.java
Output:
Name length: 8
Conditionally Returning Values With the filter() Method
The filter() method in Java's Optional class provides a way to conditionally return values based on a predicate. If a value is present in the Optional and it matches the predicate, the Optional is returned as-is; if the value does not match the predicate, an empty Optional is returned. This method is useful for applying conditional logic in a chain of Optional operations without needing explicit null-checks or conditional statements.
Basic Usage of filter() Method
Here is an example demonstrating how to use filter() to check a condition on the contained value. We will create a scenario where we check if a user's name is "admin" and perform an action based on that check.
File Name: OptionalFilterExample.java
Output:
User is an admin
Next TopicDeepseek