Optional with Examples in Java 8
Java 8 has introduced a new class in utils package Optional. This class main purpose is for handling NullPointerExceptions.
So what exactly is Optional?
As per the oracle docs – Optional is a container object which may contain a value or may not contain a value.
In simple terms it means it can have values or it can be empty.
There are many in-build methods that optional has which helps us to avoid NullPointerException.
Example:
String value1 = null;
Optional<String> value2 = Optional.empty();
if(value1!=null && value1.isEmpty()) { //Null check required
System.out.println(value1) ;
}
Optional.ofNullable(value2).ifPresent(value -> System.out.println(value)); //Null check is done by optional
Method | Explanation |
empty() | Returns an empty optional instance |
filter(Predicate<? super T> predicate) | If the value matches it returns optional value or returns optional empty |
flatMap(Function<? super T, Optional<U>> mapper) | Mapping function if value exists or optional empty |
get() | Gets the optional value if present or throws NoSuchElementException |
ifPresent(Consumer<? super T> consumer) | If optional value is present, proceed with consumer invocation or will not perform any operation |
isPresent() | Returns a boolean value, if value present returns true or false. |
map(Function<? super T, ? extends U> mapper) | Applies mapping function if the value is present |
of(T value) | Returns the optional value |
ofNullable(T value) | Returns a value if present or empty optional |
orElse(T other) | If value not present it returns the orElse value of other |
orElseGet(Supplier<? extends T> other) | Returns value if present or invokes other and returns the value |
orElseThrow(Supplier<? extends X> exceptionSupplier) | Returns value if present or throws the exception |
There also common methods in optional like toString() and hashcode().
Declaring an Optional
Declaring an empty Optional,
Optional<String> value = Optional.empty();
In the above we have declared an Empty Optional, so what does empty optional mean?
Empty Optional?
Optional.empty() is just an object of optional, means
Optional<?> EMPTY = new Optional<>();
Declaring a value for optional:
We cannot declare the string value directly for an Optional<String>, if we try the below
Optional<String> value2 = "value2"; //Compile time error - Wrap it using Optional
So how can we declare a value for an Optional variable?
There are 2 ways of declaring value for optional variables,
- Optional.of(value)
- Optional.ofNullable(value)
What is the difference between these two?
Optional.of(“value”) will throw an exception if the value is null. Where as Optional.ofNullable will continue even if the value is null.

public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
From the implementation, Optional.of(value), requires a NonNull object and will throw NullPointerException if the value is null.
Implementation of Optional.ofNullable(value):
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
From the implementation, Optional.ofNullable will return an empty Optional if the value is null. (Will not throw exception).
Filter in Optional:
Internal Implementation of Filter:
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
Now let us see with an example,
Optional<String> value3 = Optional.ofNullable(null);
System.out.println(value3.filter(val -> val.contains("a"))); // condition is null
In the above example, val is null so the predicate failed.
Filtering in String,
Optional<String> value3 = Optional.ofNullable("Alpha");
System.out.println("Filter 1: "+value3.filter(val -> val.contains("z")));
System.out.println("Filter 2: "+value3.filter(val -> val.contains("a")));
If the value is not available it will return an Empty Optional.
Output:

Filtering from List of String,
Optional<List<String>> nameList = Optional.of(Arrays.asList("Alpha", "Beta", "Charlie", "Delta"));
System.out.println(Optional.ofNullable(nameList).map(String::valueOf)
.filter(name -> name.contains("l")));
Output:

[…] How can we declare Optional and usage of Filter – here […]