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

In Java 9, few static methods: stream(), or(), and ifPresentOrElse() have added to Optional 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

<strong>public Optional<T> or(Supplier<? extends Optional<? extends T><!--? extends Optional<? extends T-->> supplier)</strong>

Example

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

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

Output

<strong>Value: TutorialsPoint
Value: Not Present</strong>
Updated on: 2020-04-17T17:40:48+05:30

931 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements