Importance of Optional.or() method in Java 9?

JavaObject Oriented ProgrammingProgramming

In Java 9,  few static methods: stream(), or(), and ifPresentOrElse() have added to Optional<T> class. The introduction of an Optional class solves the null pointer exception.

Optional.or() method returns an Optional describing the value if a value is present, otherwise returns an Optional produced by the supplying function. 

Syntax

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

Example

import java.util.Optional;
import java.util.function.Supplier;

public class OptionalOrTest {
   public static void main(String args[]) {
      Optional<String> optional = Optional.of("TutorialsPoint");
      Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
      optional = optional.or(supplierString);
      optional.ifPresent(x -> System.out.println("Value: " + x));
      optional = Optional.empty();
      optional = optional.or(supplierString);
      optional.ifPresent(x -> System.out.println("Value: " + x));
   }
}

Output

Value: TutorialsPoint
Value: Not Present
raja
Published on 17-Apr-2020 21:10:48
Advertisements