Purpose of using Optional ifPresentOrElse Method in Java 9



The improvement of ifPresentOrElse() method in Optional class is that accepts two parameters, Consumer and Runnable. The purpose of of using ifPresentOrElse() method is that if an Optional contains a value, the function action is called on the contained value, i.e. action.accept (value), which is consistent with ifPresent() method. The difference from the ifPresent() method is that ifPresentOrElse() has a second parameter, emptyAction. If Optional contains no value, then ifPresentOrElse() method calls emptyAction, i.e. emptyAction.run().

Syntax

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

Example

import java.util.Optional;

public class IfPresentOrElseMethodTest {
   public static void main(String args[]) {
      Optional<Integer> optional = Optional.of(1);

      optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
                                    System.out.println("Not Present"));

      optional = Optional.empty();

      optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
                                    System.out.println("Not Present"));
   }
}

Output

Value: 1
Not Present
Updated on: 2020-02-25T07:45:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements