How To Achieve Functional Style of Java 8 Optional.ifPresent and Optional.else

Java 8 Optional class provides various methods to handle errors that are likely to be caused by any methods returning “null” references or “no result“.

In this tutorial, you can find different options in the Java 8 Optional class for handling the functional style of checking object presence and handling if the value is not present with examples.

Using Optional.ifPresentOrElse()

The Optional.ifPresentOrElse() method checks for value presence in an object; if present, it performs an action, or else it will perform another empty action.

Syntax

    void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)

To check for a value presence using Optional.ifPresentOrElse().

  • Initialize an Optional variable.
  • Pass the value to Optional.ifPresentOrElse() method to check for null.
  • If value is not null then expected action is executed.
  • If value is empty/null then the empty action is executed.

Code

    Optional<String> name = Optional.empty();
    name.ifPresentOrElse((value)->System.out.println(value),()-> System.out.println("Name is not present, Please assign assign a name"));

    name = Optional.of("Jessica");
    name.ifPresentOrElse((value)->System.out.println(value),()-> System.out.println("Name is not present"));

Output

    Name is not present, Please assign a name
    Jessica

In the first example, the value is found empty and negative case is intimated with a message. In second case, the actual value is printed.

Use this method when negative case needs to be intimated.
This method is available since Java 9

Using Optional.ifPresent()

The Java 8 Optional.ifPresent() accepts the consumer argument and performs the operation if the value is present; else, it does nothing. So chain operation cannot be performed on the result.
Syntax

    void ifPresent(Consumer<? super T> action)

To check for a value presence using Optional.ifPresent().

  • Initialize an Optional variable.
  • Pass the value to Optional.ifPresentOrElse() method to check for null.
  • If value is not null then expected action is executed.
  • If value is empty/null then no action will be performed.

Code

    Optional<String> name = Optional.of("Jessica");
    name.ifPresent(System.out::println);

Output

    Jessica

Use this method when only positive case flow needs to be handled without to worry about negative case or no negative case is expected cases

Using Optional.orElse()

The Java 8 Optional.orElse() method helps in returning an alternate/default value when no value is present, maybe null. If the value is present, it returns the actual value to the caller.

Syntax

    public T orElse(T other)

To check for a value presence using Optional.orElse().

  • Initialize an Optional variable.
  • Pass the value to Optional.OrElse() method to check for null.
  • If value is not null then expected value is returned.
  • If value is empty/null then default value will be returned.

Code

    Optional<List> emptyDirectionList = Optional.empty();
    emptyDirectionList.orElse(Arrays.asList("North","East","South","West")).forEach(System.out::println);

Output

    North
    East
    South
    West

Use this method to handle negative case with some predefined default values for further processing

Using Optional.orElseGet()

The Optional.orElseGet() is similar to the Optional.orElse() method. Still, the difference is Optional.orElseGet() accepts Java 8 Supplier as an argument, and when the value is found null, it returns the result produced by the supplier operation.

Syntax

    public T orElseGet(Supplier<? extends T> supplier)

To check for a value presence using Optional.orElseGet().

  • Initialize an Optional variable.
  • Pass the value to Optional.orElseGet() method to check for null.
  • If value is not null then expected value is returned.
  • If value is null/empty then a value produced by supplier function will be returned.

Code

    Optional<String> name = Optional.ofNullable(null);
    Supplier<String> supplier = ()-> "dummy value";
    System.out.println(name.orElseGet(supplier));

    name = Optional.of("Jessica");        //assigning a value
    System.out.println(name.orElseGet(supplier));

Output

    dummy value
    Jessica

The object(name) is initially null, so the value(“dummy value”) is returned based on the supplier operation. Later name object is assigned a value(“Jessica”), which produces the new value instead of the value returned by the supplier operation.

Check this tutorial for understanding the difference between Optional.orElse() and Optional.orElseGet().

Use this method to handle negative case with some values that needs to be calculated and used for the further processing

Using Optional.elseThrow()

The Java 8 Optional.elseThrow() method throws exception, when value is null/empty. If the value is present, it returns the value.

Syntax

    public T orElseThrow(Supplier<? extends X> exceptionSupplier)

To check for a value presence using Optional.elseThrow().

  • Initialize an Optional variable.
  • Pass the value to Optional.elseThrow() method to check for null.
  • If value is not null then expected value is returned.
  • If value is empty/null then exception will be thrown based on the supplier function.

Code

    Optional<List> optionalList = Optional.empty();
    optionalList.orElseThrow();

Output

    Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.base/java.util.Optional.orElseThrow(Optional.java:377)
    at com.techmam.javatutorials.java8.Java4OptionalIfPresent.Java4.main(Java4.java:52)

The below example explains how to throw a user-defined exception using Optional.orElseThrow(),

Code

    Optional<List> optionalList = Optional.empty();
    optionalList.orElseThrow(()-> new RuntimeException("List is empty, add value"));

Output

    Exception in thread "main" java.lang.RuntimeException: List is empty, add value

Use this method to stop/interrupt the flow on negative case.
This method is available since Java 10

Related Topics

Leave a Comment