Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8080418

Add Optional.or()

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 9
    • None
    • core-libs
    • b89

        Currently there is no simple way to execute a supplier if current Optional is empty,
        that can be seen as the the dual of flatMap() that executes a function if the current Optional is not empty.

        A possible workaround is to use
          map(Optional::of).orElseGet(supplier)
        which while working create an unnecessary Optional and is less readable.

        The proposed implementation (by Paul Sandoz):
        public Optional<T> or(Supplier<Optional<T>> mapper) {
              Objects.requireNonNull(mapper);
              if (isPresent()) {
                  return this;
              } else {
                  return Objects.requireNonNull(mapper.get());
              }
          }

        For more information, here is the relevant discussion on core-dev:
        http://mail.openjdk.java.net/pipermail/core-libs-dev/2015-April/032904.html

              psandoz Paul Sandoz
              forax RĂ©mi Forax
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

                Created:
                Updated:
                Resolved: