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