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