In this article, we’ll explore Java Optional class which was introduced in Java 8.
Java Optional
- One of the most frequently exception in java programming is NullPointerException. A Null value often represents an absence of value which has to be handled before proceeding with the usual business logic, which leads to unnecessary null checks.
- To handle such boiler plate code for null check situations, Java 8 introduced
Optional
class. In this article, we’ll look into details how Java 8 Optional class API helps us to deal with null values. - Java 8 stream API and collection methods can return
Optional
objects. It may or may not contain a non-null value. There are various methods available in the API to deal with the Optional value in a convenient and reliable manner. - Java Optional is a final class.
Java 8 Optional Example
Let’s look at an example to get the clear idea when it would be helpful to use the objects of Optional
class.
1 2 3 4 5 6 7 8 9 |
List<String> listOfStrings = Arrays.asList("Mark", "Howard", "Anthony D'Cornian"); Optional<String> largeString = listOfStrings.stream().filter(str -> str.length() > 10).findAny(); largeString.ifPresent(System.out::println); Optional<String> veryLargeString = listOfStrings.stream().filter(str -> str.length() > 20).findAny(); veryLargeString.ifPresent(System.out::println); |
Output:
1 2 3 |
<span style="color: #008000;"><strong><code> Anthony D'Cornian </code></strong></span> |
As we can see, we want to filter the list of strings and get a value whose length is greater than a threshold value.
Such values may or may not exist in the list. Optional
API would be a perfect choice to use in such situations. As you can see it has ifPresent
method which lets us define what to do with the value, if we get any.
In our case, veryLargeString
will not contain any value so nothing will get printed.
Java 8 Optional API provides several such methods. In the next sections, we’ll explore them in detail.
Java Optional Methods
static Optional empty()
: It creates and returns an emptyOptional
instance.boolean isPresent()
: It return true if there is a value present, otherwise false.
1234Optional<String> empty = Optional.empty();System.out.println(empty.isPresent());
123falsevoid ifPresent(Consumer consumer)
: If a value is present, this method invokes the specified consumer with the value, otherwise does nothing. As we can see, in our first example:
1largeString.ifPresent(System.out::println);
gave output:
123Anthony D'CornianT get()
: If a value is present in the Optional, this method returns the value, otherwise throws NoSuchElementException. As you might have gussed
123System.out.println(largeString.get());
will also print
123Anthony D'CornianT orElse(T otherValue)
: This method returns the value if present, otherwise returns the otherValue provided in the argument. When we are not sure whetherOptional
will contain value, it’s always good idea to use this method rather than simpleget()
.
1234Optional<String> empty = Optional.empty();System.out.println(empty.orElse("Default Value"));
will print:
123Default Value
There is alsoorElseGet(Supplier other)
method available, which calls supplier function or executes lambda to get the value instead of returning hard coded value.
123System.out.println(empty.orElseGet(() -> "Default Value"));
will also print the same value.static Optional<T> of(T value)
: It returns an Optional with the specified present non-null value.
123Optional<String> opt = Optional.of("static value");Optional filter(Predicate predicate)
: It takes a predicate as an argument and returns an Optional object. If condition of the predicate is met, then the Optional is returned as is, Otherwise it will return an emptyOptional
.
1234567Optional<Integer> intOptional = Optional.of(34);Optional<Integer> evenIntOptional = intOptional.filter(i -> i % 2 == 0);System.out.println(evenIntOptional.orElse(0));Optional<Integer> oddIntOptional = intOptional.filter(i -> i % 2 != 0);System.out.println(oddIntOptional.orElse(0));
Output:
123<span style="color: #008000;"><strong><code>34</code></strong></span>
There are also equals()
, hashcode()
and toString()
methods available in the Optional API.
Java 9 Optional Class enhancements
Java 9 introduced few extra methods in Optional class:
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
: If a value is present, performs the given action with the value, otherwise performs the given empty-based action.public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier): If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
public Stream<T> stream()
: If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.
That’s all for the Java Optional class. You should also check out java 8 features.
Reference: API Doc