Java Optional

Filed Under: Java

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 Optional, Java 8 Optional

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.


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:


Anthony D'Cornian

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

  1. static Optional empty(): It creates and returns an empty Optional instance.
  2. boolean isPresent(): It return true if there is a value present, otherwise false.

    
    Optional<String> empty = Optional.empty();
    System.out.println(empty.isPresent());
    
    
    false
    
  3. void 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:

    largeString.ifPresent(System.out::println);

    gave output:

    
    Anthony D'Cornian
    
  4. T get(): If a value is present in the Optional, this method returns the value, otherwise throws NoSuchElementException. As you might have gussed

    
    System.out.println(largeString.get());
    

    will also print

    
    Anthony D'Cornian
    
  5. T orElse(T otherValue): This method returns the value if present, otherwise returns the otherValue provided in the argument. When we are not sure whether Optional will contain value, it’s always good idea to use this method rather than simple get().

    
    Optional<String> empty = Optional.empty();
    System.out.println(empty.orElse("Default Value"));
    

    will print:

    
    Default Value
    

    There is also orElseGet(Supplier other) method available, which calls supplier function or executes lambda to get the value instead of returning hard coded value.

    
    System.out.println(empty.orElseGet(() -> "Default Value"));
    

    will also print the same value.

  6. static Optional<T> of(T value): It returns an Optional with the specified present non-null value.

    
    Optional<String> opt = Optional.of("static value");
    
  7. 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 empty Optional.

    
    Optional<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:

    
    34
    0
    

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:

  1. 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.
  2. 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.
  3. 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

Comments

  1. Yogesh Nandwana says:

    Very good info on Optional API. Thank you so much,

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages