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