1 /*
   2  * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util;
  26 
  27 import java.util.function.Consumer;
  28 import java.util.function.Function;
  29 import java.util.function.Predicate;
  30 import java.util.function.Supplier;
  31 import java.util.stream.Stream;
  32 
  33 /**
  34  * A container object which may or may not contain a non-{@code null} value.
  35  * If a value is present, {@code isPresent()} returns {@code true} and
  36  * {@code get()} returns the value.
  37  *
  38  * <p>Additional methods that depend on the presence or absence of a contained
  39  * value are provided, such as {@link #orElse(Object) orElse()}
  40  * (returns a default value if no value is present) and
  41  * {@link #ifPresent(Consumer) ifPresent()} (performs an
  42  * action if a value is present).
  43  *
  44  * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
  45  * class; use of identity-sensitive operations (including reference equality
  46  * ({@code ==}), identity hash code, or synchronization) on instances of
  47  * {@code Optional} may have unpredictable results and should be avoided.
  48  *
  49  * @apiNote
  50  * {@code Optional} is primarily intended for use as a method return type where
  51  * there is a clear need to represent "no result," and where using {@code null}
  52  * is likely to cause errors. A variable whose type is {@code Optional} should
  53  * never itself be {@code null}; it should always point to an {@code Optional}
  54  * instance.
  55  *
  56  * @param <T> the type of value
  57  * @since 1.8
  58  */
  59 public final class Optional<T> {
  60     /**
  61      * Common instance for {@code empty()}.
  62      */
  63     private static final Optional<?> EMPTY = new Optional<>();
  64 
  65     /**
  66      * If non-null, the value; if null, indicates no value is present
  67      */
  68     private final T value;
  69 
  70     /**
  71      * Constructs an empty instance.
  72      *
  73      * @implNote Generally only one empty instance, {@link Optional#EMPTY},
  74      * should exist per VM.
  75      */
  76     private Optional() {
  77         this.value = null;
  78     }
  79 
  80     /**
  81      * Returns an empty {@code Optional} instance.  No value is present for this
  82      * {@code Optional}.
  83      *
  84      * @apiNote
  85      * Though it may be tempting to do so, avoid testing if an object is empty
  86      * by comparing with {@code ==} against instances returned by
  87      * {@code Optional.empty()}.  There is no guarantee that it is a singleton.
  88      * Instead, use {@link #isPresent()}.
  89      *
  90      * @param <T> The type of the non-existent value
  91      * @return an empty {@code Optional}
  92      */
  93     public static<T> Optional<T> empty() {
  94         @SuppressWarnings("unchecked")
  95         Optional<T> t = (Optional<T>) EMPTY;
  96         return t;
  97     }
  98 
  99     /**
 100      * Constructs an instance with the described value.
 101      *
 102      * @param value the non-{@code null} value to describe
 103      * @throws NullPointerException if value is {@code null}
 104      */
 105     private Optional(T value) {
 106         this.value = Objects.requireNonNull(value);
 107     }
 108 
 109     /**
 110      * Returns an {@code Optional} describing the given non-{@code null}
 111      * value.
 112      *
 113      * @param value the value to describe, which must be non-{@code null}
 114      * @param <T> the type of the value
 115      * @return an {@code Optional} with the value present
 116      * @throws NullPointerException if value is {@code null}
 117      */
 118     public static <T> Optional<T> of(T value) {
 119         return new Optional<>(value);
 120     }
 121 
 122     /**
 123      * Returns an {@code Optional} describing the given value, if
 124      * non-{@code null}, otherwise returns an empty {@code Optional}.
 125      *
 126      * @param value the possibly-{@code null} value to describe
 127      * @param <T> the type of the value
 128      * @return an {@code Optional} with a present value if the specified value
 129      *         is non-{@code null}, otherwise an empty {@code Optional}
 130      */
 131     public static <T> Optional<T> ofNullable(T value) {
 132         return value == null ? empty() : of(value);
 133     }
 134 
 135     /**
 136      * If a value is present, returns the value, otherwise throws
 137      * {@code NoSuchElementException}.
 138      *
 139      * @apiNote
 140      * The methods {@link #orElse(Object) orElse} and
 141      * {@link #orElseGet(Supplier) orElseGet}
 142      * are generally preferable to this method, as they return a substitute
 143      * value if the value is absent, instead of throwing an exception.
 144      *
 145      * @return the non-{@code null} value described by this {@code Optional}
 146      * @throws NoSuchElementException if no value is present
 147      * @see Optional#isPresent()
 148      */
 149     public T get() {
 150         if (value == null) {
 151             throw new NoSuchElementException("No value present");
 152         }
 153         return value;
 154     }
 155 
 156     /**
 157      * If a value is present, returns {@code true}, otherwise {@code false}.
 158      *
 159      * @return {@code true} if a value is present, otherwise {@code false}
 160      */
 161     public boolean isPresent() {
 162         return value != null;
 163     }
 164 
 165     /**
 166      * If a value is present, performs the given action with the value,
 167      * otherwise does nothing.
 168      *
 169      * @param action the action to be performed, if a value is present
 170      * @throws NullPointerException if value is present and the given action is
 171      *         {@code null}
 172      */
 173     public void ifPresent(Consumer<? super T> action) {
 174         if (value != null) {
 175             action.accept(value);
 176         }
 177     }
 178 
 179     /**
 180      * If a value is present, performs the given action with the value,
 181      * otherwise performs the given empty-based action.
 182      *
 183      * @param action the action to be performed, if a value is present
 184      * @param emptyAction the empty-based action to be performed, if no value is
 185      *        present
 186      * @throws NullPointerException if a value is present and the given action
 187      *         is {@code null}, or no value is present and the given empty-based
 188      *         action is {@code null}.
 189      * @since 9
 190      */
 191     public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
 192         if (value != null) {
 193             action.accept(value);
 194         } else {
 195             emptyAction.run();
 196         }
 197     }
 198 
 199     /**
 200      * If a value is present, and the value matches the given predicate,
 201      * returns an {@code Optional} describing the value, otherwise returns an
 202      * empty {@code Optional}.
 203      *
 204      * @param predicate the predicate to apply to a value, if present
 205      * @return an {@code Optional} describing the value of this
 206      *         {@code Optional}, if a value is present and the value matches the
 207      *         given predicate, otherwise an empty {@code Optional}
 208      * @throws NullPointerException if the predicate is {@code null}
 209      */
 210     public Optional<T> filter(Predicate<? super T> predicate) {
 211         Objects.requireNonNull(predicate);
 212         if (!isPresent()) {
 213             return this;
 214         } else {
 215             return predicate.test(value) ? this : empty();
 216         }
 217     }
 218 
 219     /**
 220      * If a value is present, returns an {@code Optional} describing (as if by
 221      * {@link #ofNullable}) the result of applying the given mapping function to
 222      * the value, otherwise returns an empty {@code Optional}.
 223      *
 224      * <p>If the mapping function returns a {@code null} result then this method
 225      * returns an empty {@code Optional}.
 226      *
 227      * @apiNote
 228      * This method supports post-processing on {@code Optional} values, without
 229      * the need to explicitly check for a return status.  For example, the
 230      * following code traverses a stream of URIs, selects one that has not
 231      * yet been processed, and creates a path from that URI, returning
 232      * an {@code Optional<Path>}:
 233      *
 234      * <pre>{@code
 235      *     Optional<Path> p =
 236      *         uris.stream().filter(uri -> !isProcessedYet(uri))
 237      *                       .findFirst()
 238      *                       .map(Paths::get);
 239      * }</pre>
 240      *
 241      * Here, {@code findFirst} returns an {@code Optional<URI>}, and then
 242      * {@code map} returns an {@code Optional<Path>} for the desired
 243      * URI if one exists.
 244      *
 245      * @param mapper the mapping function to apply to a value, if present
 246      * @param <U> The type of the value returned from the mapping function
 247      * @return an {@code Optional} describing the result of applying a mapping
 248      *         function to the value of this {@code Optional}, if a value is
 249      *         present, otherwise an empty {@code Optional}
 250      * @throws NullPointerException if the mapping function is {@code null}
 251      */
 252     public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
 253         Objects.requireNonNull(mapper);
 254         if (!isPresent()) {
 255             return empty();
 256         } else {
 257             return Optional.ofNullable(mapper.apply(value));
 258         }
 259     }
 260 
 261     /**
 262      * If a value is present, returns the result of applying the given
 263      * {@code Optional}-bearing mapping function to the value, otherwise returns
 264      * an empty {@code Optional}.
 265      *
 266      * <p>This method is similar to {@link #map(Function)}, but the mapping
 267      * function is one whose result is already an {@code Optional}, and if
 268      * invoked, {@code flatMap} does not wrap it within an additional
 269      * {@code Optional}.
 270      *
 271      * @param <U> The type of value of the {@code Optional} returned by the
 272      *            mapping function
 273      * @param mapper the mapping function to apply to a value, if present
 274      * @return the result of applying an {@code Optional}-bearing mapping
 275      *         function to the value of this {@code Optional}, if a value is
 276      *         present, otherwise an empty {@code Optional}
 277      * @throws NullPointerException if the mapping function is {@code null} or
 278      *         returns a {@code null} result
 279      */
 280     public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) {
 281         Objects.requireNonNull(mapper);
 282         if (!isPresent()) {
 283             return empty();
 284         } else {
 285             @SuppressWarnings("unchecked")
 286             Optional<U> r = (Optional<U>) mapper.apply(value);
 287             return Objects.requireNonNull(r);
 288         }
 289     }
 290 
 291     /**
 292      * If a value is present, returns an {@code Optional} describing the value,
 293      * otherwise returns an {@code Optional} produced by the supplying function.
 294      *
 295      * @param supplier the supplying function that produces an {@code Optional}
 296      *        to be returned
 297      * @return returns an {@code Optional} describing the value of this
 298      *         {@code Optional}, if a value is present, otherwise an
 299      *         {@code Optional} produced by the supplying function.
 300      * @throws NullPointerException if the supplying function is {@code null} or
 301      *         produces a {@code null} result
 302      * @since 9
 303      */
 304     public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) {
 305         Objects.requireNonNull(supplier);
 306         if (isPresent()) {
 307             return this;
 308         } else {
 309             @SuppressWarnings("unchecked")
 310             Optional<T> r = (Optional<T>) supplier.get();
 311             return Objects.requireNonNull(r);
 312         }
 313     }
 314 
 315     /**
 316      * If a value is present, returns a sequential {@link Stream} containing
 317      * only that value, otherwise returns an empty {@code Stream}.
 318      *
 319      * @apiNote
 320      * This method can be used to transform a {@code Stream} of optional
 321      * elements to a {@code Stream} of present value elements:
 322      * <pre>{@code
 323      *     Stream<Optional<T>> os = ..
 324      *     Stream<T> s = os.flatMap(Optional::stream)
 325      * }</pre>
 326      *
 327      * @return the optional value as a {@code Stream}
 328      * @since 9
 329      */
 330     public Stream<T> stream() {
 331         if (!isPresent()) {
 332             return Stream.empty();
 333         } else {
 334             return Stream.of(value);
 335         }
 336     }
 337 
 338     /**
 339      * If a value is present, returns the value, otherwise returns
 340      * {@code other}.
 341      *
 342      * @param other the value to be returned, if no value is present.
 343      *        May be {@code null}.
 344      * @return the value, if present, otherwise {@code other}
 345      */
 346     public T orElse(T other) {
 347         return value != null ? value : other;
 348     }
 349 
 350     /**
 351      * If a value is present, returns the value, otherwise returns the result
 352      * produced by the supplying function.
 353      *
 354      * @param supplier the supplying function that produces a value to be returned
 355      * @return the value, if present, otherwise the result produced by the
 356      *         supplying function
 357      * @throws NullPointerException if no value is present and the supplying
 358      *         function is {@code null}
 359      */
 360     public T orElseGet(Supplier<? extends T> supplier) {
 361         return value != null ? value : supplier.get();
 362     }
 363 
 364     /**
 365      * If a value is present, returns the value, otherwise throws an exception
 366      * produced by the exception supplying function.
 367      *
 368      * @apiNote
 369      * A method reference to the exception constructor with an empty argument
 370      * list can be used as the supplier. For example,
 371      * {@code IllegalStateException::new}
 372      *
 373      * @param <X> Type of the exception to be thrown
 374      * @param exceptionSupplier the supplying function that produces an
 375      *        exception to be thrown
 376      * @return the value, if present
 377      * @throws X if no value is present
 378      * @throws NullPointerException if no value is present and the exception
 379      *          supplying function is {@code null}
 380      */
 381     public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
 382         if (value != null) {
 383             return value;
 384         } else {
 385             throw exceptionSupplier.get();
 386         }
 387     }
 388 
 389     /**
 390      * Indicates whether some other object is "equal to" this {@code Optional}.
 391      * The other object is considered equal if:
 392      * <ul>
 393      * <li>it is also an {@code Optional} and;
 394      * <li>both instances have no value present or;
 395      * <li>the present values are "equal to" each other via {@code equals()}.
 396      * </ul>
 397      *
 398      * @param obj an object to be tested for equality
 399      * @return {@code true} if the other object is "equal to" this object
 400      *         otherwise {@code false}
 401      */
 402     @Override
 403     public boolean equals(Object obj) {
 404         if (this == obj) {
 405             return true;
 406         }
 407 
 408         if (!(obj instanceof Optional)) {
 409             return false;
 410         }
 411 
 412         Optional<?> other = (Optional<?>) obj;
 413         return Objects.equals(value, other.value);
 414     }
 415 
 416     /**
 417      * Returns the hash code of the value, if present, otherwise {@code 0}
 418      * (zero) if no value is present.
 419      *
 420      * @return hash code value of the present value or {@code 0} if no value is
 421      *         present
 422      */
 423     @Override
 424     public int hashCode() {
 425         return Objects.hashCode(value);
 426     }
 427 
 428     /**
 429      * Returns a non-empty string representation of this {@code Optional}
 430      * suitable for debugging.  The exact presentation format is unspecified and
 431      * may vary between implementations and versions.
 432      *
 433      * @implSpec
 434      * If a value is present the result must include its string representation
 435      * in the result.  Empty and present {@code Optional}s must be unambiguously
 436      * differentiable.
 437      *
 438      * @return the string representation of this instance
 439      */
 440     @Override
 441     public String toString() {
 442         return value != null
 443             ? String.format("Optional[%s]", value)
 444             : "Optional.empty";
 445     }
 446 }