Differences between Optional.ifPresentOrElse() and Optional.or() methods in Java 9?

JavaObject Oriented ProgrammingProgramming

Both Optional.ifPresentOrElse() and Optional.or() methods have introduced in Java 9 version to improve its functionality. The Optional.ifPresentOrElse() method checks if the value is present, apply action with value, else return empty action whereas Optional.or() method checks if the value is present, return option contains value, else return Optional applies to Supplier funciton. The Optional.ifPresentOrElse() method contains two parameters, Consumer and Runnable whereas Optional.or() method contains only one parameter, Supplier.

Syntax of Optional.ifPresentOrElse():

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

Example

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

public class IfPresentOrElseMethodTest {
   public static void main(String args[]) {
      optionalIsPresent();
      optionalIsEmpty();
   }
   private static void optionalIsPresent() {
      Optional<String> optional = Optional.of("Test");
      AtomicInteger successCounter = new AtomicInteger();
      AtomicInteger emptyOptionalsCounter = new AtomicInteger();

      optional.ifPresentOrElse(x -> successCounter.incrementAndGet(), () ->       emptyOptionalsCounter.incrementAndGet());

      System.out.println(successCounter.get());
      System.out.println(emptyOptionalsCounter.get());
   }
   private static void optionalIsEmpty() {
      Optional optional = Optional.empty();
      AtomicInteger successCounter = new AtomicInteger();
      AtomicInteger emptyOptionalsCounter = new AtomicInteger();

      optional.ifPresentOrElse(x -> successCounter.incrementAndGet(), () -> emptyOptionalsCounter.incrementAndGet());

      System.out.println(successCounter.get());
      System.out.println(emptyOptionalsCounter.get())
   }
}

Output

1
0
0
1


Syntax of Optional.or():

public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)

Example

import java.util.Optional;

public class OptionalOrMethodTest {
   public static void main(String args[]) {
      optionalIsPresent();
      optionalIsEmpty();
   }
   private static void optionalIsPresent() {
      Optional<String> optional1 = Optional.of("Test1");
      Optional<String> optional2 = Optional.of("Test2");

      Optional<String> optional3 = optional1.or(() -> optional2);
      System.out.println(optional3.get());
   }
   private static void optionalIsEmpty() {
      Optional<String> optional1 = Optional.empty();
      Optional<String> optional2 = Optional.of("Test2");

      Optional<String> optional3 = optional1.or(() -> optional2);
      System.out.println(optional3.get());
   }
}

Output

Test1
Test2
raja
Published on 25-Feb-2020 17:12:26
Advertisements